简体   繁体   English

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

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

I have a function that takes a column p of a data.frame dat and sums the similar values:我有一个函数,它采用 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)  
}

This works fine when run individually.这在单独运行时工作正常。

> 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

But when I try to run it with through a list of separate data.frames (which include 'SOM_C')但是当我尝试通过单独的 data.frames 列表(包括“SOM_C”)运行它时

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

It throws the following error.它引发以下错误。

> 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.

You should not collect several data frames using c() .您不应该使用c()收集多个数据帧。 You should use list() .您应该使用list() So the following fix should work:因此,以下修复应该有效:

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

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

Compare the differences:比较差异:

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.

相关问题 R中的lapply和data.frame - lapply and data.frame in R R:使用lapply创建新列和值,并在data.frame列表中应用嵌套,输出错误 - R:create new column and value using lapply & apply nested on data.frame list, wrong output 将函数应用于单个R data.frame列:lapply和apply不起作用-寻找与Python的DataFrame.apply(…)等效的R - Applying a function to a single R data.frame column: lapply and apply not working - looking for R equivalent to Python's DataFrame.apply(…) 使用函数在R data.frame中添加列 - Using a function to add a column in R data.frame R:将列推入data.frame函数 - R: Pushing column into data.frame function R - 将变量向量列表转换为data.frame,并使用嵌套lapply附加列 - R - transform a list of variable vectors to data.frame with additional column by nested lapply 在 R 中使用 lapply 时在数据框中添加一列 - Add a column into the data frame when using lapply in R 使用R检索data.frame中具有序列名称的列 - Using R to retrieve the column in data.frame with column name in the sequence 使用lapply()函数查找R中数据帧中每一行的均值 - Using lapply()-function to find the mean of every row in data frame in R 使用一个data.frame中的数据为R中另一个data.frame中的新列生成值 - Using data in one data.frame to generate values for a new column in another data.frame in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM