如何在 R 中从长格式重塑为宽格式时创建新的列名?
How to create new column names while reshaping in R from long format to wide format?
我想将一些数据从长格式重塑为宽格式,但令我困惑的是如何根据原始长格式中的特定列重命名新列。
Name <- c("Brian","Brian","Brian")
Age <- c(22,22,22)
Date <- c("2017.1.3","2017.1.3","2017.1.4")
School <- c("PH","En","Math")
Score <- c(100,99,98)
Course <- c("Epi751","Python","Statistics")
data <- data.frame(Name, Age, Date, School, Score, Course)
data
而 table 看起来像
Name Age Date School Score Course
1 Brian 22 2017.1.3 PH 100 Epi751
2 Brian 22 2017.1.3 En 99 Python
3 Brian 22 2017.1.4 Math 98 Statistics
那我怎么改成这样呢?
Name Age Date_Epi751 School_Epi751 Score_Epi751 Date_Python School_Python Score_Python Date_Statistics School_Statistics Score_Statistics
Brian 22 2017.1.3 PH 100 2017.1.3 En 99 2017.1.4 Math 98
嗯,你可以试试reshape
> reshape(data, timevar="Course", idvar = "Name", direction="wide")
Name Age.Epi751 Date.Epi751 School.Epi751 Score.Epi751 Age.Python
1 Brian 22 2017.1.3 PH 100 22
Date.Python School.Python Score.Python Age.Statistics Date.Statistics
1 2017.1.3 En 99 22 2017.1.4
School.Statistics Score.Statistics
1 Math 98
这里有一个关于如何使用整形的参考,HOW CAN I RESHAPE MY DATA IN R?
我想将一些数据从长格式重塑为宽格式,但令我困惑的是如何根据原始长格式中的特定列重命名新列。
Name <- c("Brian","Brian","Brian")
Age <- c(22,22,22)
Date <- c("2017.1.3","2017.1.3","2017.1.4")
School <- c("PH","En","Math")
Score <- c(100,99,98)
Course <- c("Epi751","Python","Statistics")
data <- data.frame(Name, Age, Date, School, Score, Course)
data
而 table 看起来像
Name Age Date School Score Course
1 Brian 22 2017.1.3 PH 100 Epi751
2 Brian 22 2017.1.3 En 99 Python
3 Brian 22 2017.1.4 Math 98 Statistics
那我怎么改成这样呢?
Name Age Date_Epi751 School_Epi751 Score_Epi751 Date_Python School_Python Score_Python Date_Statistics School_Statistics Score_Statistics
Brian 22 2017.1.3 PH 100 2017.1.3 En 99 2017.1.4 Math 98
嗯,你可以试试reshape
> reshape(data, timevar="Course", idvar = "Name", direction="wide")
Name Age.Epi751 Date.Epi751 School.Epi751 Score.Epi751 Age.Python
1 Brian 22 2017.1.3 PH 100 22
Date.Python School.Python Score.Python Age.Statistics Date.Statistics
1 2017.1.3 En 99 22 2017.1.4
School.Statistics Score.Statistics
1 Math 98
这里有一个关于如何使用整形的参考,HOW CAN I RESHAPE MY DATA IN R?