Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201941

use values from a column as index to extract a value from another column in R

$
0
0

Suppose I have this dataframe df:

df <- data_frame(A = c(1:10), B = c(21:30), C = c(NA, NA, NA, 1, 8, 3, NA, 4, 7, 3)) 

       A     B     C
   <int> <int> <dbl>
 1     1    21    NA
 2     2    22    NA
 3     3    23    NA
 4     4    24     1
 5     5    25     8
 6     6    26     3
 7     7    27    NA
 8     8    28     4
 9     9    29     7
10    10    30     3

I want to use the non-NA values in column C as index to extract the values in column B to create a new column D. The resulting dataframe should look like this:

      A     B     C     D
   <int> <int> <dbl> <dbl>
 1     1    21    NA    NA
 2     2    22    NA    NA
 3     3    23    NA    NA
 4     4    24     1    21
 5     5    25     8    28
 6     6    26     3    23
 7     7    27    NA    NA
 8     8    28     4    24
 9     9    29     7    27
10    10    30     3    23

I tried df %>% mutate(D = df[C,]) and df %>% mutate(D = df[C,B]) but both code doesn't give me the result I want. Thanks!


Viewing all articles
Browse latest Browse all 201941

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>