不使用c(…)从列表中粘贴矢量值,然后打印到文件中

时间:2022-05-01 21:29:19

I have two datasets, one containing a list of indices and the other containing a list of numbers.

我有两个数据集,一个包含索引列表,另一个包含数字列表。

v <- c("a", "b", "c", "d")

lst <- list(c("4", "75097", "72607", "72607", "62572"), NA, c("5", "113116", "5372", "5372", "11767"), c("4", "11767", "85822", "85822", "82080", "82080", "77055"))

I would like to print them side by side and feed the result into a txt file, with the following code:

我想将它们并排打印出来,并将结果输入到一个txt文件中,代码如下:

connect <- file("new.txt")
writeLines(paste(v, lst, sep=" "), connect)
close(connect)

The result I get is this:

我得到的结果是:

a c("4", "75097", "72607", "72607", "70692", "70692", "69112", "69112", "62572")
b NA
c c("5", "113116", "5372", "5372", "11767", "11767", "85822", "85822", "82080", "82080", "77055")
......

How do I print the vectorial strings on the lst without the c(...) to give this result?

我如何在没有c(…)的情况下打印出该结果的矢量字符串?

a 4 75097 72607 72607 62572 
b NA 
c 5 113116 5372 5372 11767
d 4 11767 85822 85822 82080 82080 77055 

1 个解决方案

#1


3  

We can use Map to paste the list elements with the corresponding elements of vector

我们可以使用Map将列表元素粘贴到相应的vector元素中。

out <- Map(function(x, y) paste(x, paste(y, collapse=' '), sep= ' '), v, lst) 

Or use sapply to loop over the list, paste the contents together and then paste with the vector

或者使用sapply对列表进行循环,将内容粘贴到一起,然后使用向量进行粘贴

out <- paste(v, sapply(lst, paste, collapse=' '))

For printing, we can use cat

对于打印,我们可以使用cat。

cat(unlist(out, use.names = FALSE), sep="\n")
#a 4 75097 72607 72607 62572
#b 5 113116 5372 5372 11767
#c 4 11767 85822 85822 82080 82080 77055
#d 5 79414 79867 79867 80161 78893 79867 79867 80650 80650 80161

#1


3  

We can use Map to paste the list elements with the corresponding elements of vector

我们可以使用Map将列表元素粘贴到相应的vector元素中。

out <- Map(function(x, y) paste(x, paste(y, collapse=' '), sep= ' '), v, lst) 

Or use sapply to loop over the list, paste the contents together and then paste with the vector

或者使用sapply对列表进行循环,将内容粘贴到一起,然后使用向量进行粘贴

out <- paste(v, sapply(lst, paste, collapse=' '))

For printing, we can use cat

对于打印,我们可以使用cat。

cat(unlist(out, use.names = FALSE), sep="\n")
#a 4 75097 72607 72607 62572
#b 5 113116 5372 5372 11767
#c 4 11767 85822 85822 82080 82080 77055
#d 5 79414 79867 79867 80161 78893 79867 79867 80650 80650 80161