繁体   English   中英

将 lapply 与选择一列 data.frame 的 R 函数一起使用

[英]Using lapply with an R function that selects a column of data.frame

我有一个函数,它采用 data.frame dat的列p并对相似值求和:

response <- function(dat, p){
    y = dat[p]
    sums = table(y)
    sums_df = as.data.frame(sums)
    #sums_df$rfreq = (sums_df$Freq/sum(sums_df$Freq))*100
    #sums_df$rfreq = round(sums_df$rfreq, digits = 0)
    #sums_df = sums_df[1:4, c(1,3)]
  return(sums_df)  
}

这在单独运行时工作正常。

> response(SOM_C, "f76a")
  f76a Freq
1    1    5
2    2   51
3    3   14
4    4    6
5    5   29
6   97    1
7   99    7

但是当我尝试通过单独的 data.frames 列表(包括“SOM_C”)运行它时

plist <- c(SOM_V, SOM_SD, SOM_C, SOM_L, SOM_M, SOM_KD, SOM_MP, SOM_SvD)

它引发以下错误。

> output <- lapply(plist, response, p = "f76a")

Error in `vec_slice()`:
! Can't use character names to index an unnamed vector.
Run `rlang::last_error()` to see where the error occurred.

您不应该使用c()收集多个数据帧。 您应该使用list() 因此,以下修复应该有效:

plist <- list(SOM_V, SOM_SD, SOM_C, SOM_L, SOM_M, SOM_KD, SOM_MP, SOM_SvD)

output <- lapply(plist, response, p = "f76a")

比较差异:

dat <- data.frame(a = 1:2, b = c("x", "y"))

## becomes a list of vectors
c(dat, dat)
#$a
#[1] 1 2
#
#$b
#[1] "x" "y"
#
#$a
#[1] 1 2
#
#$b
#[1] "x" "y"

## correct: a list of two data frames
list(dat, dat)

暂无
暂无

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

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