ここは新しいです。私はちょうど私がこの質問を持っているR.列エントリを列に変換するR
を学び始めました:
name = c("John", "John","John","John","Mark","Mark","Mark","Mark","Dave", "Dave","Dave","Dave")
color = c("red", "blue", "green", "yellow","red", "blue", "green", "yellow","red", "blue", "green", "yellow")
value = c(1,2,1,3,5,5,3,2,4,6,7,8)
df = data.frame(name, color, value)
#View(df)
df
# name color value
# 1 John red 1
# 2 John blue 2
# 3 John green 1
# 4 John yellow 3
# 5 Mark red 5
# 6 Mark blue 5
# 7 Mark green 3
# 8 Mark yellow 2
# 9 Dave red 4
# 10 Dave blue 6
# 11 Dave green 7
# 12 Dave yellow 8
と私はそれが次のようになりたい::
私はデータフレームを持っていると仮定し
# names red blue green yellow
#1 John 1 2 1 3
#2 Mark 5 5 3 2
#3 Dave 4 6 7 8
ことは、最初の列(名前)のエントリは一意になり、2番目の列(色)のレベルは新しい列になり、これらの新しい列に入るエントリは対応する列元のデータフレームの3番目の列(値)に行を追加します。
私は、次を使用してこれを実現することができます
library(dplyr)
df = df %>%
group_by(name) %>%
mutate(red = ifelse(color == "red", value, 0.0),
blue = ifelse(color == "blue", value, 0.0),
green = ifelse(color == "green", value, 0.0),
yellow = ifelse(color == "yellow", value, 0.0)) %>%
group_by(name) %>%
summarise_each(funs(sum), red, blue, green, yellow)
df
name red blue green yellow
1 Dave 4 6 7 8
2 John 1 2 1 3
3 Mark 5 5 3 2
しかし、レベルの多くは、色の列に存在する場合、これは理想的ではないでしょう。私はそれをどうやってやりますか?
ありがとうございました!
からから
dcast
を使用することができます。ありがとうございました! – chowching