如何在 R 数据框中的行中创建具有最大大小字符串值的列?
要创建行中具有最大大小字符串值的列,我们可以使用apply函数并通过创建一个函数来定义字符串的最大值,如下例所示。如果所有列中的字符数相同或存在一些关系,则输出将是第一个。
示例1
考虑以下数据框-
x1<−sample(c("UK","USA","India"),20,replace=TRUE) x2<−sample(c("China","Egypt"),20,replace=TRUE) df1<−data.frame(x1,x2) df1输出结果
x1 x2 1 India China 2 India Egypt 3 India Egypt 4 India China 5 USA China 6 UK Egypt 7 UK Egypt 8 UK Egypt 9 India Egypt 10 India China 11 USA China 12 India China 13 India Egypt 14 UK China 15 India China 16 UK China 17 India China 18 UK China 19 USA China 20 USA China
在df1的每一行中创建一个具有最大文本的列-
示例
df1$LargeText <− apply(df1,1, function(x) x[which.max(nchar(x))]) df1输出结果
x1 x2 LargeText 1 India China India 2 India Egypt India 3 India Egypt India 4 India China India 5 USA China China 6 UK Egypt Egypt 7 UK Egypt Egypt 8 UK Egypt Egypt 9 India Egypt India 10 India China India 11 USA China China 12 India China India 13 India Egypt India 14 UK China China 15 India China India 16 UK China China 17 India China India 18 UK China China 19 USA China China 20 USA China China
例2
y1<−sample(c("Female","Male"),20,replace=TRUE) y2<−sample(c("Female","Male"),20,replace=TRUE) df2<−data.frame(y1,y2) df2输出结果
y1 y2 1 Male Female 2 Male Female 3 Female Male 4 Female Male 5 Female Female 6 Female Male 7 Male Male 8 Female Female 9 Female Female 10 Female Female 11 Male Male 12 Male Female 13 Male Male 14 Male Female 15 Female Male 16 Female Female 17 Male Female 18 Female Female 19 Female Male 20 Female Female
在df2的每一行中创建一个具有最大文本的列-
示例
df2$LargeText<−apply(df2,1, function(x) x[which.max(nchar(x))]) df2输出结果
y1 y2 LargeText 1 Male Female Female 2 Male Female Female 3 Female Male Female 4 Female Male Female 5 Female Female Female 6 Female Male Female 7 Male Male Male 8 Female Female Female 9 Female Female Female 10 Female Female Female 11 Male Male Male 12 Male Female Female 13 Male Male Male 14 Male Female Female 15 Female Male Female 16 Female Female Female 17 Male Female Female 18 Female Female Female 19 Female Male Female 20 Female Female Female