Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
循环以在r中标记标记及其对应的值_R_String - Fatal编程技术网

循环以在r中标记标记及其对应的值

循环以在r中标记标记及其对应的值,r,string,R,String,这应该很简单;然而,我不能把它弄对。 我得到了以下列表: list <- list(c("sofa", "couch"), c("fridge"), c("desk", "table", "brown"), c("window", "clean"), c("speaker")) list在R基中,您可以取消列出列表,以获取单词,并根据长度重复每个列表的串联元素 data.frame(word = unlist(li

这应该很简单;然而,我不能把它弄对。 我得到了以下列表:

list <- list(c("sofa", "couch"), 
         c("fridge"),
         c("desk", "table", "brown"),
         c("window", "clean"),
         c("speaker"))

list在R基中,您可以
取消列出
列表
,以获取
单词
,并根据长度重复每个
列表
的串联元素

data.frame(word = unlist(list), 
           label = rep(sapply(list, paste, collapse = " "), lengths(list)))

#     word            label
#1    sofa       sofa couch
#2   couch       sofa couch
#3  fridge           fridge
#4    desk desk table brown
#5   table desk table brown
#6   brown desk table brown
#7  window     window clean
#8   clean     window clean
#9 speaker          speaker

另一个选项是
stack

stack(setNames(list, sapply(list, paste, collapse = " ")))
#   values              ind
#1    sofa       sofa couch
#2   couch       sofa couch
#3  fridge           fridge
#4    desk desk table brown
#5   table desk table brown
#6   brown desk table brown
#7  window     window clean
#8   clean     window clean
#9 speaker          speaker

在快速重写我的问题时,我发现了代码的错误。 然而,Ronak和markus以前提供的解决方案更紧凑,更有意义

使用循环执行此操作 我发现有些参数丢失了

for(i in 1:length(list)){
  for(j in 1:length(list[[i]])){
    value <- data.frame(word = list[[i]][j], label = str_c(list[[i]], collapse = " "), stringsAsFactors = FALSE)
    table <- rbind(table, value)
  }
}
for(1中的i:长度(列表)){
对于(1中的j:长度(列表[[i]])){

谢谢,你的回答很快。我打算删除这个问题,因为在编辑问题时,我发现了一些错误。但是,你的解决方案更简单。
stack(setNames(list, sapply(list, paste, collapse = " ")))
#   values              ind
#1    sofa       sofa couch
#2   couch       sofa couch
#3  fridge           fridge
#4    desk desk table brown
#5   table desk table brown
#6   brown desk table brown
#7  window     window clean
#8   clean     window clean
#9 speaker          speaker
for(i in 1:length(list)){
  for(j in 1:length(list[[i]])){
    value <- data.frame(word = list[[i]][j], label = str_c(list[[i]], collapse = " "), stringsAsFactors = FALSE)
    table <- rbind(table, value)
  }
}