Home > Mobile >  Merge variables and set old variable name as new variable
Merge variables and set old variable name as new variable

Time:09-01

My data set looks like this:

variable1 variable2 variable3
value1 NA NA
NA value2 NA
NA NA value3

I want to transform it into this:

variable value
variable1 value1
variable2 value2
variable3 value3

Is there any function I can use?

CodePudding user response:

Use tidyr::pivot_longer with values_drop_na = TRUE:

library(tidyr)
pivot_longer(df, everything(), names_to = "variable", values_drop_na = TRUE)
  variable  value 
  <chr>     <chr> 
1 variable1 value1
2 variable2 value2
3 variable3 value3

CodePudding user response:

Another option using gather from tidyr with na.rm = TRUE:

df <- read.table(text = "variable1  variable2   variable3
value1  NA  NA
NA  value2  NA
NA  NA  value3
", header = TRUE)

library(tidyr)
gather(df, key = "variable", value = "value", na.rm = TRUE)
#>    variable  value
#> 1 variable1 value1
#> 5 variable2 value2
#> 9 variable3 value3

Created on 2022-08-31 with reprex v2.0.2

CodePudding user response:

In base R, we can use stack

na.omit(stack(df1)[2:1])
        ind values
1 variable1 value1
5 variable2 value2
9 variable3 value3

data

df1 <- structure(list(variable1 = c("value1", NA, NA), variable2 = c(NA, 
"value2", NA), variable3 = c(NA, NA, "value3")),
 class = "data.frame", row.names = c(NA, 
-3L))
  • Related