I have a data frame which looks like this
> test <- data.frame(ID = c(1,2,3,4,5),ATTR1 = c("A","A","B","C","C"),ATTR2 = c("A2","A2","B2","B2","B2"),ATTR3 = c("A3","A3","A3","B3","B3") )
> test
ID ATTR1 ATTR2 ATTR3
1 1 A A2 A3
2 2 A A2 A3
3 3 B B2 A3
4 4 C B2 B3
5 5 C B2 B3
From this data frame I am trying to obtain dataframe
> desired_frame <- data.frame(ID = c(1,2,3,4,5),A = c(1,1,0,0,0),B = c(0,0,1,0,0),C = c(0,0,0,1,1),A2 = c(1,1,0,0,0),B2 = c(0,0,1,1,1),A3 = c(1,1,1,0,0), B3 = c(0,0,0,1,1))
> desired_frame
ID A B C A2 B2 A3 B3
1 1 1 0 0 1 0 1 0
2 2 1 0 0 1 0 1 0
3 3 0 1 0 0 1 1 0
4 4 0 0 1 0 1 0 1
5 5 0 0 1 0 1 0 1
I tried using dcast however I was unsuccessful
test$PROXY <- rep(1,nrow(test))
> dcast(test, ID ~ ATTR1 + ATTR2 + ATTR3, fun.aggregate = mean, value.var = "PROXY")
ID A_A2_A3 B_B2_A3 C_B2_B3
1 1 1 NaN NaN
2 2 1 NaN NaN
3 3 NaN 1 NaN
4 4 NaN NaN 1
5 5 NaN NaN 1
Any help would be greatly appreciated
this is a long route to the destination !
library(tidyr)
df = melt(test, id.vars = "ID", measure.vars = c("ATTR1", "ATTR2", "ATTR3"))
df1 = spread(df, value, variable)
cbind(df1[1], (!is.na(df1[-1]))+0)
# ID A A2 A3 B B2 B3 C
#1 1 1 1 1 0 0 0 0
#2 2 1 1 1 0 0 0 0
#3 3 0 0 1 1 1 0 0
#4 4 0 0 0 0 1 1 1
#5 5 0 0 0 0 1 1 1
Here is a base R solution with model.matrix
, lapply
, and do.call
df <- do.call(cbind, c(test[1], lapply(names(test)[-1],
function(i) model.matrix(reformulate(c(i, -1)), data=test))))
ID ATTR1A ATTR1B ATTR1C ATTR2A2 ATTR2B2 ATTR3A3 ATTR3B3
1 1 1 0 0 1 0 1 0
2 2 1 0 0 1 0 1 0
3 3 0 1 0 0 1 1 0
4 4 0 0 1 0 1 0 1
5 5 0 0 1 0 1 0 1
reformulate
with the -1 returns a formula that includes one variable and removes the intercept (allowing all factor levels to be present). model.matrix
takes this formula and constructs a matrix of the factor levels. lapply
applies this to each of the factor variables and returns a list of matrices. Finally, do.call
combines the matrices in the list as well as the ID variable. Note that this returns a matrix.
To get a data.frame instead, replace cbind
with data.frame
df <- do.call(data.frame, c(test[1], lapply(names(test)[-1],
function(i) model.matrix(reformulate(c(i, -1)), data=test))))
To rename the columns, you could use sub
:
colnames(df) <- sub("ATTR\\d+", "", colnames(df))
Another base R solution
facs <- apply(test[,-1], 2, unique)
desired_frame <- test
for(j in 1:3){
dummy <- sapply(facs[[j]], "==", test[,j+1])
desired_frame <- cbind(dummy+0, desired_frame)
}
desired_frame
## A3 B3 A2 B2 A B C ID ATTR1 ATTR2 ATTR3
## 1 1 0 1 0 1 0 0 1 A A2 A3
## 2 1 0 1 0 1 0 0 2 A A2 A3
## 3 1 0 0 1 0 1 0 3 B B2 A3
## 4 0 1 0 1 0 0 1 4 C B2 B3
## 5 0 1 0 1 0 0 1 5 C B2 B3
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.