【发布时间】:2020-07-11 01:43:51
【问题描述】:
我想在字符向量上循环一个函数。该函数将创建一个向量或一个列表,每个向量(列表)的名称将从字符向量中获取。例如。
# The data would look like:
fist second third
1 2 3
1 NA 3
1 2 3
1 2 NA
NA 2 3
# I want to create three lists/vectors such as
first <- c("1.pdf", "1.pdf", "1.pdf", "1.pdf")
second <- c("2.pdf", "2.pdf", "2.pdf", "2.pdf")
third <- c("3.pdf", "3.pdf", "3.pdf", "3.pdf")
# where, first, second, third, now are the names of the vectors. I tried the following way.
vector_names <- c("first", "second", "third")
cleanNA <- function(x){
x <- as.character(as.data.frame(t(data[paste0(x)])))
x <- na.omit(x) # remove all NA observations.
x <- paste0(x, ".pdf")
return(x)
}
# I can do this by a vector length 1.
name <- c("first")
assign(name, namef)
namef <- createlists(name)
# But once I do an lapply, it won't create the three vectors as I wanted. The lapply does run and returns what I want, but not create the three vectors.
lapply(vector_names, cleanNA)
我一直在寻找这类问题很多次,感觉 R 并没有真正提供在循环中生成新向量的好方法。我对吗?谢谢。
【问题讨论】:
-
您好,我已经添加了一个示例,谢谢。