我是一名数据分析初学者,目前正在学习如何在DataCamp中使用R。我希望整理一个可以在R Studio中找到的名为irsi的数据集。我想知道如何逐步清除此数据集,如下所示:
原版的:
head(iris)
Species Sepal.Length Sepal.Width Petal.Length Petal.Width
1 setosa 5.1 3.5 1.4 0.2
2 setosa 4.9 3.0 1.4 0.2
3 setosa 4.7 3.2 1.3 0.2
4 setosa 4.6 3.1 1.5 0.2
5 setosa 5.0 3.6 1.4 0.2
6 setosa 5.4 3.9 1.7 0.4
Run Code Online (Sandbox Code Playgroud)
步骤1:
> head(iris.wide)
Species Part Length Width
1 setosa Petal 1.4 0.2
2 setosa Petal 1.4 0.2
3 setosa Petal 1.3 0.2
4 setosa Petal 1.5 0.2
5 setosa Petal 1.4 0.2
6 setosa Petal 1.7 0.4
Run Code Online (Sandbox Code Playgroud)
第2步:
head(iris.tidy)
Species Part Measure Value
1 setosa Sepal Length 5.1
2 setosa Sepal Length 4.9
3 setosa Sepal Length 4.7
4 setosa Sepal Length 4.6
5 setosa Sepal Length 5.0
6 setosa Sepal Length 5.4
Run Code Online (Sandbox Code Playgroud)
请随时让我知道是否有我未明确提及的内容。任何建议将不胜感激,谢谢!
这是一个tidyverse解决方案:
head(iris) %>%
unite(Sepal, Sepal.Length, Sepal.Width) %>%
unite(Petal, Petal.Length, Petal.Width) %>%
gather(Part, Value, 1:2) %>%
separate(Value, into = c("Length", "Width"), sep = "_") %>% # <-- Step 1
gather(Measure, Value, 3:4) # <-- Step 2
Run Code Online (Sandbox Code Playgroud)
或更快:
head(iris) %>%
gather(key, value, 1:4) %>%
separate(key, into = c("Part", "Measure"))
Run Code Online (Sandbox Code Playgroud)
由于您正在学习如何操作/整理数据,因此我强烈建议您逐步进行操作,以了解每种操作的作用。