简体   繁体   English

根据 R 中某一列中的值获取 dataframe 中某个单元格的值

[英]get the value of a cell of a dataframe based on the value in one of the columns in R

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".我有一个数据框的示例,其中“a”和“b”列具有特定值,而“c”列中的值为 1 或 2。我想创建列“d”,其中的值位于该框架将位于“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.因此第一行的“d”列将包含值 1,因为“c”列中的索引为 1,对于第二行 d = 4,因为“c”列中的索引为 2,依此类推。 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? R 中的标准索引对我没有帮助,它只返回列 c 的值。我可以通过哪些方式解决我的问题?

You may can create a matrix of row and column numbers to subset values from the dataframe.您可以创建一个行号和列号矩阵,以对 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.如果输入的是tibble,需要把tibble改成dataframe才能使用上面的答案。

If you don't want to change to dataframe, here is another option using rowwise .如果您不想更改为 dataframe,这里是另一个使用rowwise的选项。

library(dplyr)

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

By using dplyr::mutate and ifelse ,通过使用dplyr::mutateifelse

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM