如果这是一个像这样的 1 行数据框:
df <- data.frame(matrix(c(60, 285, 161, 368, 476, 453, 247, 101, 62, 114),
nrow = 1))
names(df) <- c("0-10", "11-16", "17-20", "21-30", "31-40", "41-50",
"51-60", "61-70", "over70", "age_unknown")
df
> df
0-10 11-16 17-20 21-30 31-40 41-50 51-60 61-70 over70 age_unknown
1 60 285 161 368 476 453 247 101 62 114
然后一个简单的操作将以您想要的格式创建数据框:
df2 <- data.frame(age_range = names(df), number = as.numeric(df[1, ]))
df2
> df2
age_range number
1 0-10 60
2 11-16 285
3 17-20 161
4 21-30 368
5 31-40 476
6 41-50 453
7 51-60 247
8 61-70 101
9 over70 62
10 age_unknown 114
一个更简单的方法可能是转置df
使用t()
然后修复结果:
df3 <- t(df)
df3 <- cbind.data.frame(rownames(df3), df3)
rownames(df3) <- NULL
names(df3) <- c("age_range","number")
df3
> df3
age_range number
1 0-10 60
2 11-16 285
3 17-20 161
4 21-30 368
5 31-40 476
6 41-50 453
7 51-60 247
8 61-70 101
9 over70 62
10 age_unknown 114
> str(df3)
'data.frame': 10 obs. of 2 variables:
$ age_range: Factor w/ 10 levels "0-10","11-16",..: 1 2 3 4 5 6 7 8 10 9
$ number : num 60 285 161 368 476 453 247 101 62 114