简体   繁体   English

遍历列表并串联R中的字符串(语法)

[英]Looping through list and concatenating strings in R (Syntax)

I'm trying to create a loop that goes from 1 to 14. Each integer in this loop would be added to the end of the name of a newly created dataframe. 我正在尝试创建一个从1到14的循环。此循环中的每个整数都将添加到新创建的数据帧名称的末尾。 Then, it should search a column in an existing dataframe based on the concatenation of a number and text. 然后,它应该基于数字和文本的连接在现有数据框中搜索一列。 I've been searching for hours but cannot find a solution. 我一直在找几个小时,但找不到解决方案。

What I mean is: 我的意思是:

while (i <= 14) {
    "newDF" + i <- oldDf %>%
         filter(str_detect(ColumnName, "TEXT" + i)

} }

The new dataframes should look like this: 新的数据框应如下所示:

newDF1,newDF2... newDF14 newDF1,newDF2 ... newDF14

They should be created based on a concatenated string (text + i): 它们应基于串联字符串(文本+ i)创建:

text1,text2..text14 text1,text2..text14

My first challenge is to create a new dataframe based on the concatenation of text and i . 我的第一个挑战是基于text和i的串联创建一个新的数据框。 I've tried using the str_c command and the str_glue command but get the following error message. 我尝试使用str_c命令和str_glue命令,但收到以下错误消息。

Error in str_c("newDF", i)) <- oldDF: 
  target of assignment expands to non-language object


Error in str_glue("newDF{i}") <- oldDF: 
  target of assignment expands to non-language object

The major problem with your code above is that you can't have any operations to the left of your assignment operator. 上面的代码的主要问题在于,赋值运算符的左侧无法进行任何操作。

for (i in 1:14){
    assign(str_glue("newDF{i}"), oldDF %>%
         filter(str_detect(ColumnName, str_glue("TEXT{i}"))))
}

So technically, this would work even though I feel like there's a better way to do this either with nested lists or using spread and gather. 因此,从技术上讲,即使我觉得有更好的方法可以使用嵌套列表或使用散布和收集,也可以使用。 I would say more, but I don't have enough context to solve the problem. 我会说更多,但我没有足够的背景来解决问题。

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

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