如何在 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

更新于: 2021 年 2 月 9 日

114 次浏览

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告