簡體   English   中英

將組添加到 R 中的 dataframe 中的行

[英]Adding groups to rows in a dataframe in R

我想從這個轉換我的數據: current data.frame

對此:所需的data.frame

我不知道如何開始,歡迎任何幫助!

提前致謝,

米奇

一種使用reshape() melt()的解決方案

library(readr)
library(reshape)

 Data:

df<-structure(list(age_group = c("<20", ">70", "20-29", "30-39", 
"40-49", "50-59", "60-69"), no = c(19L, 1L, 447L, 196L, 92L, 
55L, 24L), yes = c(21L, 1L, 664L, 371L, 204L, 137L, 63L), total = c(2L, 
0L, 217L, 175L, 112L, 82L, 39L)), class = "data.frame", row.names = c(NA, 
-7L))

代碼:

df<-melt(C0001)
df<-as.data.frame(df)
df[order(df$age_group),]

     age_group variable value
1        <20       no    19
8        <20      yes    21
15       <20    total     2
2        >70       no     1
9        >70      yes     1
16       >70    total     0
3      20-29       no   447
10     20-29      yes   664
17     20-29    total   217
4      30-39       no   196
11     30-39      yes   371
18     30-39    total   175
5      40-49       no    92
12     40-49      yes   204
19     40-49    total   112
6      50-59       no    55
13     50-59      yes   137
20     50-59    total    82
7      60-69       no    24
14     60-69      yes    63
21     60-69    total    39

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM