将列表中的元素连接到R中新列中的特定格式

问题描述 投票:1回答:2

我有latlon坐标和相关的“subID”。我想在此数据框中创建一个新列,其中每个子ID都已粘贴为html格式。见下文:

我的数据:

                   latlon                                   subID
1 25.4034735, -80.5586135 c("S35858790", "S35858833", "S35924843")
2 26.4330582, -80.9416786              c("S35834082", "S35857972")
3 26.452893, -80.979942                                  S35686789
4 29.3339241, -94.7480679              c("S20299537", "S20300308")

我想在新列的第一行看到的内容(向右滚动):

<a href = http://www.SomeUrl.com/S35858790>S35858790</a><a href = http://www.SomeUrl.com/S35858833>S35858833</a><a href = http://www.SomeUrl.com/S35924843>S35924843</a>

第三行应该只有:

<a href = http://www.SomeUrl.com/S35686789>S35686789</a>

subID列可以是最多或超过100个子ID的列表。

r list dataframe concatenation paste
2个回答
2
投票

这与your previous question没什么不同。同样,我们可以使用基本R函数aggregate,这次使用paste来构建您想要使用的锚标记:

a_start <- '<a href = http://www.SomeUrl.com/'
a_end <- '</a>'
out <- aggregate(data=df,subID~latlon,FUN = function(t) sort(paste0(a_start, t, '>', t, a_end, collapse="")))

Demo

即使我们的自定义聚合函数对整个锚标记进行排序,它仍应正确排序,因为导致第一个subID的内容对于所有内容都是相同的。


2
投票

你也可以使用tapply虽然这给你一个矢量。

funfun=function(x)paste0("<a href = http://www.SomeUrl.com/",x,">",x,"</a>",collapse = "")
with(data,tapply(subID,latlon,funfun))
© www.soinside.com 2019 - 2024. All rights reserved.