如何在单行代码中将R数据帧中的多列转换为从整数到数字?
要将R数据帧的列从整数转换为数字,我们可以使用lapply函数。例如,如果我们有一个包含所有整数列的数据框df,则可以使用代码lapply(df,as.numeric)将所有列的数据类型转换为数字数据类型。
例1
请看以下数据帧-
set.seed(871) x1<−sample(0:1,20,replace=TRUE) x2<−sample(0:5,20,replace=TRUE) x3<−sample(1:5,20,replace=TRUE) x4<−sample(0:9,20,replace=TRUE) x5<−sample(1:10,20,replace=TRUE) df1<−data.frame(x1,x2,x3,x4,x5) df1
输出结果
x1 x2 x3 x4 x5 1 0 2 2 9 9 2 0 2 1 1 10 3 1 1 5 8 10 4 1 3 2 4 3 5 0 0 2 4 3 6 1 5 2 8 3 7 0 4 5 4 5 8 1 1 5 8 1 9 0 1 4 9 7 10 0 4 2 0 9 11 1 1 4 7 6 12 0 2 4 8 5 13 1 5 5 0 1 14 1 0 1 5 4 15 0 0 3 7 5 16 1 0 4 6 4 17 1 5 4 7 8 18 1 1 1 3 2 19 1 2 3 6 3 20 0 0 1 8 1
str(df1)
输出结果
'data.frame': 20 obs. of 5 variables: $ x1: int 0 0 1 1 0 1 0 1 0 0 ... $ x2: int 2 2 1 3 0 5 4 1 1 4 ... $ x3: int 2 1 5 2 2 2 5 5 4 2 ... $ x4: int 9 1 8 4 4 8 4 8 9 0 ... $ x5: int 9 10 10 3 3 3 5 1 7 9 ...
将df1的列转换为数字-
df1<−lapply(df1,as.numeric) str(df1)
输出结果
List of 5 $ x1: num [1:20] 0 0 1 1 0 1 0 1 0 0 ... $ x2: num [1:20] 2 2 1 3 0 5 4 1 1 4 ... $ x3: num [1:20] 2 1 5 2 2 2 5 5 4 2 ... $ x4: num [1:20] 9 1 8 4 4 8 4 8 9 0 ... $ x5: num [1:20] 9 10 10 3 3 3 5 1 7 9 ...
例2
y1<−rpois(20,10) y2<−rpois(20,8) y3<−rpois(20,5) y4<−rpois(20,2) df2<−data.frame(y1,y2,y3,y4) df2
输出结果
y1 y2 y3 y4 1 9 10 4 3 2 6 9 4 0 3 7 9 3 4 4 4 3 6 1 5 9 7 2 4 6 17 4 7 2 7 6 5 7 0 8 3 5 5 4 9 12 6 7 5 10 15 10 4 2 11 6 3 5 2 12 9 10 6 0 13 6 8 6 2 14 11 6 4 2 15 9 7 3 5 16 12 7 3 3 17 18 9 8 4 18 7 5 3 5 19 14 4 7 4 20 17 8 8 3
示例
str(df2)
输出结果
'data.frame': 20 obs. of 4 variables: $ y1: int 9 6 7 4 9 17 6 3 12 15 ... $ y2: int 10 9 9 3 7 4 5 5 6 10 ... $ y3: int 4 4 3 6 2 7 7 5 7 4 ... $ y4: int 3 0 4 1 4 2 0 4 5 2 ...
将df2的列转换为数字-
df2<−lapply(df2,as.numeric) str(df2)
List of 4 $ y1: num [1:20] 9 6 7 4 9 17 6 3 12 15 ... $ y2: num [1:20] 10 9 9 3 7 4 5 5 6 10 ... $ y3: num [1:20] 4 4 3 6 2 7 7 5 7 4 ... $ y4: num [1:20] 3 0 4 1 4 2 0 4 5 2 ...
例子3
z1<−sample(21:30,20,replace=TRUE) z2<−sample(1:50,20) z3<−sample(101:200,20) df3<−data.frame(z1,z2,z3) df3
输出结果
z1 z2 z3 1 29 32 130 2 27 26 149 3 22 11 199 4 30 28 161 5 21 36 174 6 29 8 152 7 23 23 142 8 27 22 114 9 24 45 135 10 21 34 171 11 28 40 125 12 24 42 148 13 21 43 106 14 25 1 137 15 26 7 118 16 22 2 184 17 28 4 192 18 24 38 183 19 27 31 168 20 21 3 185
示例
str(df3)
输出结果
'data.frame': 20 obs. of 3 variables: $ z1: int 29 27 22 30 21 29 23 27 24 21 ... $ z2: int 32 26 11 28 36 8 23 22 45 34 ... $ z3: int 130 149 199 161 174 152 142 114 135 171 ...
将df3的列转换为数字-
df3<−lapply(df3,as.numeric) str(df3)
输出结果
List of 3 $ z1: num [1:20] 29 27 22 30 21 29 23 27 24 21 ... $ z2: num [1:20] 32 26 11 28 36 8 23 22 45 34 ... $ z3: num [1:20] 130 149 199 161 174 152 142 114 135 171 ...
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短