首页 > 解决方案 > 使用 lapply 将单个数据框列转换为数据框列表中的数字

问题描述

我有一个数据框列表,每个 df 都有三列,所有这些列都是character. 我想要的是使用lapply(或其他*apply函数)as.numeric并将“心脏病发作”列转换为数字,但还要保留每个数据帧中的其他变量。

这是示例数据:

data <- structure(list(AK = structure(list(hospital = c("HOS_3", "HOS_4"
), state = c("AK", "AK"), `heart attack` = c("13.4", "17.7")), .Names = c("hospital", 
"state", "heart attack"), row.names = 3:4, class = "data.frame"), 
AL = structure(list(hospital = c("HOS_1", "HOS_2"), state = c("AL", 
"AL"), `heart attack` = c("14.3", "18.5")), .Names = c("hospital", 
"state", "heart attack"), row.names = 1:2, class = "data.frame"), 
AR = structure(list(hospital = c("HOS_5", "HOS_6"), state = c("AR", 
"AR"), `heart attack` = c("15.6", "16.9")), .Names = c("hospital", 
"state", "heart attack"), row.names = 5:6, class = "data.frame")), .Names = c("AK", 
"AL", "AR"))

看起来像这样:

> data
$AK
hospital state heart attack
3    HOS_3    AK         13.4
4    HOS_4    AK         17.7

$AL
hospital state heart attack
1    HOS_1    AL         14.3
2    HOS_2    AL         18.5

$AR
hospital state heart attack
5    HOS_5    AR         15.6
6    HOS_6    AR         16.9

我想要完全相同的结构,但只是将“心脏病发作”列作为数字。这是我到目前为止所尝试的(基于其他 SO 帖子和 ?docs 和玩弄)以及解释出了什么问题的评论:

lapply(c, function(x) x[3] <- as.numeric(x[[3]])) # returns list of num vectors. Dropped other cols
lapply(c, function(x) x[[3]] <- as.numeric(x[[3]])) # returns list of num vectors. Dropped other cols
rapply(c, as.numeric, classes = 'character', how='list') # Correct structure in output but converts all other cols to NA
sapply(c, function(x) x[,3] <- as.numeric(x[,3])) # returns list of num vectors. Dropped other cols
lapply(c, function(x) lapply(x[,3], as.numeric)) # returns list of num vectors of single length
lapply(c, lapply, as.numeric([[3]])) # error unexpected '[[
lapply(c, function(x) {x[[3]] <- as.numeric(x[[3]])})# returns list of num vectors. Dropped other cols
lapply(c, lapply, as.numeric, [,3]) # error unexpected '[

非常感谢帮助!另外,我想只使用基本 R(如果可能的话),所以不想引入另一个库(工作中的安全问题 - 他们并不总是允许)。非常感谢。

标签: rlapply

解决方案


您非常接近,您只需要在更改一列后返回完整的数据框。因此,如果您想按名称更改列的类别,请执行

data <- lapply(data, function(x) {x$`heart attack` <- as.numeric(x$`heart attack`);x})

或者,如果您想按位置更改课程,请执行

data <- lapply(data, function(x) {x[[3]] <- as.numeric(x[[3]]);x})

推荐阅读