将多列堆叠成单列,在R中具有单个值
stacking multiple columns into single column with single value in R
ID Time U1 U2 U3 U4
1 20 1 0 0 0
2 20 0 1 0 0
3 20 0 0 1 0
4 20 0 0 0 1
我需要保持这样的状态:
ID Time U
1 20 U1
2 20 U2
3 20 U3
4 20 U4
我试过:
X_D <- as.data.frame(X)
X_new <- stack(X_D, select = -c(ID, Time))
尝试
library(dplyr)
df <- data.frame(ID = 1:4, Time = 20, U1 = c(1,0,0,0), U2 = c(0,1,0,0), U3 = c(0,0,1,0), U4 = c(0,0,0,1))
df %>% pivot_longer(cols = 3:6, names_to = "U") %>%
filter(value == 1) %>%
select(-value)
ID Time U1 U2 U3 U4
1 20 1 0 0 0
2 20 0 1 0 0
3 20 0 0 1 0
4 20 0 0 0 1
我需要保持这样的状态:
ID Time U
1 20 U1
2 20 U2
3 20 U3
4 20 U4
我试过:
X_D <- as.data.frame(X)
X_new <- stack(X_D, select = -c(ID, Time))
尝试
library(dplyr)
df <- data.frame(ID = 1:4, Time = 20, U1 = c(1,0,0,0), U2 = c(0,1,0,0), U3 = c(0,0,1,0), U4 = c(0,0,0,1))
df %>% pivot_longer(cols = 3:6, names_to = "U") %>%
filter(value == 1) %>%
select(-value)