简体   繁体   English

R-将功能应用于相似数据列表中的特定列

[英]R - Apply a function to specific column in a list of similar data.frames

I am making a list of data.frames like so: 我正在像这样创建一个data.frames列表:

simulation_data <- vector( mode = "list", length = length(subgroups_a))

for( A in subgroups_a) { simulation_data[['A']] <- paste0(dbGetQuery(conn, "SELECT a, b, c, date FROM t WHERE a = ", A)) }

In general, how do I apply a function to a specific column which is the same across each data.frame in the list? 通常,如何将函数应用于列表中每个data.frame相同的特定列?

My specific situation is that I need to apply ymd() to the date column of each data.frame in simulation_data . 我的具体情况是,我需要申请ymd()date在每个data.frame列simulation_data My work-around currently is to just update the column each time in the for loop like so: simulation_inv[['A']]['dt'] <- ymd(simulation_inv[['A']]['dt']) , but I'd like to vectorize it if possible. 我目前的解决方法是每次仅在for循环中更新列for如下所示: simulation_inv[['A']]['dt'] <- ymd(simulation_inv[['A']]['dt']) ,但如果可能的话,我想将其向量化。

I can't figure out how to use lapply to do this, and perhaps there is an even better solution. 我不知道如何使用lapply来做到这一点,也许还有更好的解决方案。

Thanks for any help. 谢谢你的帮助。

Something like this, perhaps - 大概是这样-

DT1 = data.frame(A=20130101:20130103,B=letters[1:3])
DT2 = data.frame(A=20130104:20130105,B=letters[4:5])
l = list(DT1,DT2)

l2 <- lapply(l, function(x) cbind(x,as.Date(as.character(x$A),'%Y%m%d')))

Where l looks like - l看起来像什么

> l
[[1]]
         A B
1 20130101 a
2 20130102 b
3 20130103 c

[[2]]
         A B
1 20130104 d
2 20130105 e

And l2 looks like - l2看起来像-

> l2
[[1]]
         A B as.Date(as.character(x$A), "%Y%m%d")
1 20130101 a                           2013-01-01
2 20130102 b                           2013-01-02
3 20130103 c                           2013-01-03

[[2]]
         A B as.Date(as.character(x$A), "%Y%m%d")
1 20130104 d                           2013-01-04
2 20130105 e                           2013-01-05

Using this same basic approach, you could also overwrite your earlier column, or assign a nicer column name, etc. 使用相同的基本方法,您还可以覆盖之前的列,或分配更好的列名称,等等。

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

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