【问题标题】:Create vectors within lappy (or loop)在 lappy(或循环)中创建向量
【发布时间】: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 并没有真正提供在循环中生成新向量的好方法。我对吗?谢谢。

【问题讨论】:

  • 您好,我已经添加了一个示例,谢谢。

标签: r lapply


【解决方案1】:

这是一个简化版:

cleanNA <- function(data, x){
   x <- data[[x]]
   x <- na.omit(x) 
   x <- paste0(x, ".pdf")
   return(x)
   #Or a one-liner
   #paste0(na.omit(data[[x]]), '.pdf')
}

list_vec <- lapply(vector_names, cleanNA, data = data)
list_vec

#[[1]]
#[1] "1.pdf" "1.pdf" "1.pdf" "1.pdf"

#[[2]]
#[1] "2.pdf" "2.pdf" "2.pdf" "2.pdf"

#[[3]]
#[1] "3.pdf" "3.pdf" "3.pdf" "3.pdf"

最好将数据保存在一个列表中,这样更易​​于管理,避免在全局环境中创建大量对象。但是,如果您希望它们作为单独的向量,您可以使用 list2env

list_vec <- setNames(list_vec, vector_names)
list2env(list_vec, .GlobalEnv)

数据

data <- structure(list(first = c(1L, 1L, 1L, 1L, NA), second = c(2L, 
NA, 2L, 2L, 2L), third = c(3L, 3L, 3L, NA, 3L)), class = "data.frame",
row.names = c(NA, -5L))

【讨论】:

  • 非常感谢,这适用于本示例,谢谢。如果第 2 列有 2 个 NA,第 3 列有 3 个 NA,即去掉 NA 后数据帧不平衡怎么办?这实际上是我的情况,但我没有说明这个例子。这就是为什么我想创建单独的向量。
  • 这仍然有效,因为lapply 正在返回一个列表,并且一个列表可以包含不同长度的元素。
  • 谢谢!!!! setNames 现在有效!我试图将 setnames 放在循环中但没有用,并且不知道 list2env。这解决了我的问题!! (没有那个list_vec,它不会改变数据框)>但是还是谢谢你!我应该问而不是在这上面浪费 3 个小时!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-27
  • 1970-01-01
相关资源
最近更新 更多