在 R 中操作 DataFrame 中的行和列

manipulate both rows and columns in a dataframe in R

提问人:WimK 提问时间:3/22/2023 最后编辑:WimK 更新时间:3/22/2023 访问量:23

问:

我有一个数据帧,需要先操作它,然后才能将其用于分析。数据框由不同列中的步行计数器组成,这些计数器在行中每天的小时计数。下面是一个例子:

Date/time       counter1   counter2  counter3
1/1/2016 8:00      0           2        8
1/1/2016 9:00      1           0        3
1/1/2016 10:00     5           15       1

我需要将数据帧转换为以下结构:

Date/time       counter_name       count
1/1/2016 8:00    counter 1           0 
1/1/2016 9:00    counter 1           1  
1/1/2016 10:00   counter 1           5
1/1/2016 8:00    counter 2           2
1/1/2016 9:00    counter 2           0
1/1/2016 10:00   counter 2           15
1/1/2016 8:00    counter 3           8
1/1/2016 9:00    counter 3           3
1/1/2016 10:00   counter 3           1
    

我尝试使用转置函数与列切换行,但后来我仍然不在我需要的地方,我的行有名称,但我的行不需要有名称。有人可以帮助我吗?先谢谢你!

R DataFrame tidyr 数据操作

评论


答:

0赞 Andre Wildberg 3/22/2023 #1

尝试pivot_longer

library(dplyr)
library(tidyr)

df %>% 
  pivot_longer(-"Date/time", names_to="counter_name", values_to="count")
# A tibble: 9 × 3
  `Date/time`    counter_name count
  <chr>          <chr>        <int>
1 1/1/2016 8:00  counter 1        0
2 1/1/2016 8:00  counter 2        2
3 1/1/2016 8:00  counter 3        8
4 1/1/2016 9:00  counter 1        1
5 1/1/2016 9:00  counter 2        0
6 1/1/2016 9:00  counter 3        3
7 1/1/2016 10:00 counter 1        5
8 1/1/2016 10:00 counter 2       15
9 1/1/2016 10:00 counter 3        1