将函数应用于多个数据帧 [英] Apply a function to multiple dataframes

查看:59
本文介绍了将函数应用于多个数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多数据帧,其中缺失值由字符串 'NA' 表示,而 R 不会将其理解为缺失值.

I have many dataframes where missing values are denoted by the character string 'NA' which are not understood as missing by R.

冗长的解决方案是将以下函数应用于每个数据帧:

The lengthy solution would be to apply the following function to each dataframe:

mydf[mydf == 'NA'] <- NA

我想将上述函数应用于许多数据帧.

考虑以下示例:

set.seed(123)
A=as.data.frame(matrix(sample(c('NA',1:10),10*10,T),10)))
B=as.data.frame(matrix(sample(c('NA',LETTERS[1:10]),10*10,T),10))
C=as.data.frame(matrix(sample(c('NA',letters[1:10]),10*10,T),10))

我最好的尝试(不起作用):

And my best try (which does not work):

target <- list(A, B, C)
lapply(target, function(x) x[x == 'NA'] <- NA )

推荐答案

您几乎做对了.你只是忘记了 R 返回函数的最后访问元素.在您的情况下,它只是每个数据帧的一个子集,因此将您的函数设置为返回 x 并且它可以工作:

You almost got it right. You just forgot R returns the last accessed element of a function. In your case, it was only a subset of each data frame, so set your function to return x and it works:

set.seed(123)
A = as.data.frame(matrix(sample(c('NA',1:10),10*10,T),10))
B = as.data.frame(matrix(sample(c('NA',LETTERS[1:10]),10*10,T),10))
C = as.data.frame(matrix(sample(c('NA',letters[1:10]),10*10,T),10))

target = list(A, B, C)
lapply(target, function(x) {
  x[x == 'NA'] <- NA
  return(x)
})

这篇关于将函数应用于多个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆