gpt4 book ai didi

r - 仅将嵌套数据帧的一列除以整数值

转载 作者:行者123 更新时间:2023-12-01 23:55:23 25 4
gpt4 key购买 nike

我希望将数据框的第三列除以 5。这些数据框是嵌套的,如下所示:

[[44]]
Ethnicity Variant Sum
1: ASW ACCEPTOR 1
2: ASW CDS 68
3: ASW CGA_CNVWIN 1000
4: ASW CGA_MIRB 0
5: ASW DELETE 0
6: ASW DISRUPT 0
7: ASW DONOR 0
8: ASW FRAMESHIFT 0
9: ASW INSERT 1
10: ASW INTRON 54

我使用了三个命令,每个命令都成功但有脱靶效果。

lapply(ASWldtSUM,function(x)(x/5))

返回

[[44]]
Ethnicity Variant Sum
1: NA NA 0.2
2: NA NA 13.6
3: NA NA 200.0
4: NA NA 0.0
5: NA NA 0.0

它具有将所有行除以 5 的不幸影响,导致类不是 $Sum 列中的整数时出现问题。

lapply(ASWldtSUM,function(x[,3])(x/5))

具有仅返回单个向量的效果,如果这不是嵌套的数据帧数组,那么它会很好地工作,而是语句

ASWdtSUM$NEWCOL<-lapply(ASWldtSUM,function(x[,3])(x/5))

不能简单写,因为是嵌套的。

在以下语句中使用 rapply:

rapply(ASWldtSUM,function(x) if (is.integer(x)) {(x/5)})

导致结果困惑。

那么,有没有一种简单的方法可以将第 4 列附加到每个嵌套的 DataFrame,或者用该值除以 5 替换每个 DF(Sum)的第三列?

最佳答案

很简单,如果ASWldtSUM是包含数据框的列表的名字,那么你可以这样做:

lapply(ASWldtSUM,FUN=function(x) { x[,3]=x[,3]/5; return(x) })

基本上,您将(整个)第三列替换为将(整个)第三列除以五。

实践中:

> ASWldtSUM1=data.frame(Ethnicity=rep('ASW',10),Variant=c("ACCEPTOR","CDS","CGA_CNVWIN","CGA_MIRB","DELETE","DISRUPT","DONOR","FRAMESHIFT","INSERT","INTRON"), Sum=c(1,68,1000,0,0,0,0,0,1,54))
> #created a first data.frame (equal to your example)
> ASWldtSUM2=data.frame(Ethnicity=rep('ASW',10),Variant=c("ACCEPTOR","CDS","CGA_CNVWIN","CGA_MIRB","DELETE","DISRUPT","DONOR","FRAMESHIFT","INSERT","INTRON"), Sum=c(1,2,3,4,5,6,7,8,9,10))
> #created a second data.frame (with different values for the third column)
> ASWldtSUM=list(ASWldtSUM1,ASWldtSUM2)
> #created a list of data frames
> lapply(ASWldtSUM,FUN=function(x) { x[,3]=x[,3]/5; return(x) })
> #apply the function to divide third column to each nested data.frame
[[1]]
Ethnicity Variant Sum
1 ASW ACCEPTOR 0.2
2 ASW CDS 13.6
3 ASW CGA_CNVWIN 200.0
4 ASW CGA_MIRB 0.0
5 ASW DELETE 0.0
6 ASW DISRUPT 0.0
7 ASW DONOR 0.0
8 ASW FRAMESHIFT 0.0
9 ASW INSERT 0.2
10 ASW INTRON 10.8

[[2]]
Ethnicity Variant Sum
1 ASW ACCEPTOR 0.2
2 ASW CDS 0.4
3 ASW CGA_CNVWIN 0.6
4 ASW CGA_MIRB 0.8
5 ASW DELETE 1.0
6 ASW DISRUPT 1.2
7 ASW DONOR 1.4
8 ASW FRAMESHIFT 1.6
9 ASW INSERT 1.8
10 ASW INTRON 2.0
> #desired result

关于r - 仅将嵌套数据帧的一列除以整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24010366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com