gpt4 book ai didi

r - 如何跨 data.frame 列应用函数?

转载 作者:行者123 更新时间:2023-12-04 09:22:17 25 4
gpt4 key购买 nike

假设我有一个包含这样数值的数据框

AA01.AVG_Beta AA02.AVG_Beta AA03.AVG_Beta AA04.AVG_Beta AA05.AVG_Beta
1 0.15851770 0.44264830 0.46662180 0.79579230 0.555430100
2 0.87148450 0.93462340 0.92591830 0.93812860 0.942683400
3 0.60907060 0.92463760 0.62698660 0.86852790 0.457659300
4 0.10728340 0.07848221 0.06340047 0.08589865 0.118239800
5 0.72353630 0.91198210 0.87339600 0.88050440 0.902925300
6 0.52616050 0.57114700 0.29431990 0.56032260 0.530103800
7 0.50321330 0.78129660 0.26986880 0.77825860 0.924097500
8 0.47808630 0.11267250 0.30519660 0.36128510 0.741012600
9 0.17698960 0.11461960 0.57776080 0.37801670 0.465766500
10 0.01268375 0.01370702 0.01194124 0.01227029 0.009222724

我想使用这些条件将每行中的所有数值更改为字母

平均 beta 0-0.2 变为 AA,平均 beta 0.4-0.6 变为 AB,平均 beta 0.8-1 变为 BB

所以我写了类似的东西

apply(table, 2, function(x) ifelse (x>0 & x< 0.2, "AA",ifelse(x>0.4 & x<0.6,"AB",
+ "BB")) )

但是我明白了

AA01.AVG_Beta AA02.AVG_Beta AA03.AVG_Beta AA04.AVG_Beta AA05.AVG_Beta
[1,] "AA" NA NA NA NA
[2,] "BB" NA NA NA NA
[3,] "BB" NA NA NA NA
[4,] "AA" NA NA NA NA
[5,] "BB" NA NA NA NA
[6,] "AB" NA NA NA NA
[7,] "AB" NA NA NA NA
[8,] "AB" NA NA NA NA
[9,] "AA" NA NA NA NA
[10,] "AA" NA NA NA NA

只有第一列 也许我遗漏了与 for 循环相关的内容?

提前致谢

最佳答案

你可以使用cut:

x <- c(0.15,0.2,0.4,0.6,0.8,1.0)
cut(x,c(0,0.2,0.4,0.6,0.8,1.0),labels=c("AA",NA,"AB",NA,"BB"))
[1] AA AA <NA> AB <NA> BB
Levels: AA <NA> AB <NA> BB
Warning message:
In `levels<-`(`*tmp*`, value = c("AA", NA, "AB", NA, "BB")) :
duplicated levels will not be allowed in factors anymore

请注意警告,因为我对分区中的两个间隙都使用了 NA。

关于r - 如何跨 data.frame 列应用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8255663/

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