简体   繁体   中英

Combine info from two columns and extend data frame in R

i have a data frame like this:

  n  s     b
1 2 aa  TRUE
2 3 bb FALSE
3 5 cc  TRUE

How do i extend the data frame to something like this by combining some of the info.

    n    tags
1 2_s      aa
2 3_s      bb
3 5_s      cc
4 2_b      TRUE
5 3_b      FALSE
6 5_b      TRUE
.
.
.

See how the n column is now a combination of its original name and that of a column name and the tags being their original values.

We gather the 's', 'b' columns into 'long' format and then do an unite

library(tidyverse)
gather(df1, key, tags, s:b) %>% 
     unite(n, n, key)
#    n  tags
#1 2_s    aa
#2 3_s    bb
#3 5_s    cc
#4 2_b  TRUE
#5 3_b FALSE
#6 5_b  TRUE

data

df1 <- structure(list(n = c(2L, 3L, 5L), s = c("aa", "bb", "cc"), b = c(TRUE, 
 FALSE, TRUE)), class = "data.frame", row.names = c("1", "2", 
 "3"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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