Home > Net >  get the value of a cell of a dataframe based on the value in one of the columns in R
get the value of a cell of a dataframe based on the value in one of the columns in R

Time:09-28

I have an example of a data frame in which columns "a" and "b" have certain values, and in column "c" the values are 1 or 2. I would like to create column "d" in which the value found in the frame will be located at the index specified in column "c".

x = data.frame(a = c(1:10), b = c(3:12), c = seq(1:2))
x
    a  b c
1   1  3 1
2   2  4 2
3   3  5 1
4   4  6 2
5   5  7 1
6   6  8 2
7   7  9 1
8   8 10 2
9   9 11 1
10 10 12 2

thus column "d" for the first row will contain the value 1, since the index in column "c" is 1, for the second row d = 4, since the index in column "c" is 2, and so on. I was not helped by the standard indexing in R, it just returns the value of the column c. in what ways can I solve my problem?

CodePudding user response:

You may can create a matrix of row and column numbers to subset values from the dataframe.

x$d <- x[cbind(1:nrow(x), x$c)]
x

#    a  b c  d
#1   1  3 1  1
#2   2  4 2  4
#3   3  5 1  3
#4   4  6 2  6
#5   5  7 1  5
#6   6  8 2  8
#7   7  9 1  7
#8   8 10 2 10
#9   9 11 1  9
#10 10 12 2 12

If the input is tibble, you need to change the tibble to dataframe to use the above answer.

If you don't want to change to dataframe, here is another option using rowwise.

library(dplyr)

x <- tibble(x)
x %>% rowwise() %>% mutate(d = c_across()[c])

CodePudding user response:

By using dplyr::mutate and ifelse,

x %>% mutate(d = ifelse(c == 1, a, b))

    a  b c  d
1   1  3 1  1
2   2  4 2  4
3   3  5 1  3
4   4  6 2  6
5   5  7 1  5
6   6  8 2  8
7   7  9 1  7
8   8 10 2 10
9   9 11 1  9
10 10 12 2 12
  •  Tags:  
  • r
  • Related