Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
81 views
in Technique[技术] by (71.8m points)

What code should be written to create a new variable from observations containing the same content in the R column?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is a base R approach. We can first find all unique variable values from the data frame. Then, sapply over that vector and generate a new column for each value. Finally, we can rbind this new data frame of 0/1 valued columns to the original data frame.

cols <- sort(unique(df$variable))
df2 <- sapply(cols, function(x) ifelse(df$variable == x, 1, 0))
df <- cbind(df, df2)
df

  variable B C D
1        D 0 0 1
2        D 0 0 1
3        B 1 0 0
4        C 0 1 0
5        B 1 0 0
6        D 0 0 1
7        C 0 1 0
8        C 0 1 0
9        D 0 0 1

Data:

df <- data.frame(variable=c("D", "D", "B", "C", "B",
                            "D", "C", "C", "D"),
                 stringsAsFactors=FALSE)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...