Reputation: 25
My data frame (x) is:
c1 c2
Aa 02
Bb 03
Cc 02
I'd like to create a column c3 copying the observation in c1 based on the row number in c2:
c1 c2 c3
Aa 02 Bb
Bb 03 Cc
Cc 02 Bb
I'm working with base R and I can't download packages.
Thank you!
Upvotes: 1
Views: 104
Reputation: 146239
Using this data:
x = read.table(text = 'c1 c2
Aa 02
Bb 03
Cc 02 ', header = T)
Here's a solution:
x$c3 = x$c1[as.numeric(as.character(x$c2))]
# c1 c2 c3
# 1 Aa 2 Bb
# 2 Bb 3 Cc
# 3 Cc 2 Bb
as.numeric(as.character())
is a very safe way to convert something to numeric--it will work whether the source is factor
or character
(or already numeric
). Though if you look at the class, class(x$c2)
you can be more judicious about exactly what conversion is needed.
Upvotes: 3