简体   繁体   English

R:在 r 中创建一个新列,其中包含来自另一列的连接值

[英]R: Create a new column in r with concatenated values from another column

Here is a test dataset with one column of company names.这是一个包含一列公司名称的测试数据集。

df <- data.frame(companyName= c("Apple", "Microsoft", "Perspectives", "Jet", "Icontel AG","Intel"))

I would like to concatenate these names and add them to a new column in the dataframe我想连接这些名称并将它们添加到数据框中的新列

I tried the following using a for loop:我使用 for 循环尝试了以下操作:

df$contain <- NA #create a new column

df$contain <- for (i in 1:nrow(df)){
  paste('Contains(TR.CommonName,\'', df[i,1], '\')')
  }

The prompt is not giving me any error and the command above is simply deleting the new created column.提示没有给我任何错误,上面的命令只是删除新创建的列。 I could not figure out what I am doing wrong and any help is appreciated.我无法弄清楚我做错了什么,任何帮助表示赞赏。

my desired output would be我想要的输出是

      companyName    contain
1     Apple          Contains(TR.CommonName,Apple)
2     Microsoft      Contains(TR.CommonName,Microsoft)
3     Perspectives   Contains(TR.CommonName,Perspectives)
4     Jet            Contains(TR.CommonName,Jet)
5     Icontel AG     Contains(TR.CommonName,Icontel AG)
6     Intel          Contains(TR.CommonName,Intel)

你可以简单地这样做:

df$contains <- paste0("Contains(TR.CommonName,", df$companyName, ")")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM