imdevskp
imdevskp

Reputation: 2223

I have a dataframe with a column that is a vector. I want to get the last element and store it in a new column. How can I do it?

what I have dataframe that looks like this

df>
    col1       col2
     1     c('a', 'b', 'c')
     2     c('r', 't')
     3     c('x', 'y')

What I want a dataframe that looks like this

df>
    col1       col2             col3
     1     c('a', 'b', 'c')      'c'
     2     c('r', 't')           't'
     3     c('x', 'y')           'y'

Upvotes: 0

Views: 49

Answers (2)

slava-kohut
slava-kohut

Reputation: 4233

Here is an example:

df <- data.frame(C = I(list(list("a","b"),list("a","b","c"))))
df$D <- sapply(df$C, function(x) x[length(x)])

Output

C D
1 a, b b
2 a, b, c c

Upvotes: 1

Rajith Thennakoon
Rajith Thennakoon

Reputation: 4130

Try this

df$col3 <- sapply(df$col2,function(s) as.vector(s)[length(s)])

Upvotes: 1

Related Questions