How to create a column with largest size string value in rows in an R data frame?


To create a column with largest size string value in rows, we can use apply function and define the size of the string for the largest value by creating a function as shown in the below examples. If the number of characters in all the columns are same or there exists some ties then the output will be the first one.

Example1

 Live Demo

Consider the below data frame −

x1<−sample(c("UK","USA","India"),20,replace=TRUE)
x2<−sample(c("China","Egypt"),20,replace=TRUE)
df1<−data.frame(x1,x2)
df1

Output

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

Creating a column with largest text in each row of df1 −

Example

df1$LargeText <− apply(df1,1, function(x) x[which.max(nchar(x))])
df1

Output

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

Example2

 Live Demo

y1<−sample(c("Female","Male"),20,replace=TRUE)
y2<−sample(c("Female","Male"),20,replace=TRUE)
df2<−data.frame(y1,y2)
df2

Output

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

Creating a column with largest text in each row of df2 −

Example

df2$LargeText<−apply(df2,1, function(x) x[which.max(nchar(x))])
df2

Output

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

Updated on: 09-Feb-2021

82 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements