简体   繁体   English

遍历数据集的每一行和每一列

[英]Iterate through each row and column of a dataset

I'm kind of new to R, and I need to convert several datasets into one big mysql table. 我是R的新手,我需要将几个数据集转换为一个大mysql表。

What I need is to iterate each row of the dataset and get each row adding the label of the column and value of the row as well as its id into a new row. 我需要的是迭代数据集的每一行,并让每一行将列的标签和行的值以及其ID添加到新行中。

Example: Lets say the dataset below: 示例:假设下面的数据集:

      ID    NAME    AGE
1     2589  Joe     31
2     2590  Joseph  15
3     2591  Maria   40

I need to turn it into: 我需要将其转换为:

      id   question  answer
1     2589 NAME      Joe
2     2589 AGE       31
3     2590 NAME      Joseph
4     2590 AGE       15
5     2591 NAME      Maria
6     2591 AGE       40

I need to do this to several datasets that doesn't have the same number of columns, but the result dataset should have the same format. 我需要对没有相同列数的几个数据集执行此操作,但是结果数据集应具有相同的格式。

Can anyone help me? 谁能帮我?

Try tidyr::gather() . 尝试tidyr::gather() For your example assuming a data frame mydata : 对于您的示例,假设数据框为mydata

library(tidyr)
mydata %>% 
  gather(question, answer, -ID)

Convert your table to long format using tidyr::gather then sort by ID 使用tidyr::gather将表格转换为长格式,然后按ID排序

library(dplyr)
library(tidyr)

txt <- "ID    NAME    AGE
1     2589  Joe     31
2     2590  Joseph  15
3     2591  Maria   40"

df <- read.table(text = txt, header = TRUE)

df %>% 
  gather(key = "question", value = "answer", -ID) %>% 
  arrange(ID)

#>     ID question answer
#> 1 2589     NAME    Joe
#> 2 2589      AGE     31
#> 3 2590     NAME Joseph
#> 4 2590      AGE     15
#> 5 2591     NAME  Maria
#> 6 2591      AGE     40

Created on 2018-03-21 by the reprex package (v0.2.0). reprex软件包 (v0.2.0)于2018-03-21创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM