英文:
Reshaping data frame with old variables to be new rownames
问题
我需要将我的数据重塑成这样的方式,即在列中包含两个不同年份的值,以便我可以计算变化。主要思想是用户可以选择两个不同的年份,并查看不同KPI的变化。
假设这是我的数据:
df <- data.frame(
PERIOD = c(2020, 2021),
map = c(1, 2),
mac = c(1, 4)
)
我希望新的数据框有两列(年份2020和年份2021),而“map”和“mac”则成为一个名为“kpi”的新变量的值。
英文:
I need to reshape my data on a way that in the columns I have the values for two different years, so I can calculate the variation. The main idea is that the user can select two different years and view the variation for different KPI's.
Suppose this is my data:
df <- data.frame(
PERIOD = c(2020, 2021),
map = c(1, 2),
mac = c(1, 4)
)
I would like the new data frame to have two columns (year 2020, year 2021) and "map" "mac" to be the values of a new variable called "kpi".
答案1
得分: 5
你还可以通过使用基本的R代码来进行转置和整理名称来完成这个操作:
setNames(as.data.frame(t(df)[-1,]), df[[1]])
#> 2020 2021
#> map 1 2
#> mac 1 4
(注意:代码部分没有翻译。)
英文:
You could also do this in base R by transposing and tidying the names:
setNames(as.data.frame(t(df)[-1,]), df[[1]])
#> 2020 2021
#> map 1 2
#> mac 1 4
答案2
得分: 3
Using transpose
from data.table
data.table::transpose(df, make.names = 'PERIOD', keep.names = 'kpi')
kpi 2020 2021
1 map 1 2
2 mac 1 4
(Note: I've provided the translation as requested, but it seems that the code you provided is already in English, so there's no translation needed for this code snippet.)
英文:
Using transpose
from data.table
data.table::transpose(df, make.names = 'PERIOD', keep.names = 'kpi')
kpi 2020 2021
1 map 1 2
2 mac 1 4
答案3
得分: 2
library(tidyr)
pivot_longer(df, cols = -PERIOD, names_to = "kpi") |
pivot_wider(names_from = PERIOD, names_prefix = "year")
Output
kpi year2020 year2021
1 map 1 2
2 mac 1 4
英文:
library(tidyr)
pivot_longer(df, cols = -PERIOD, names_to = "kpi") |>
pivot_wider(names_from = PERIOD, names_prefix = "year")
Output
kpi year2020 year2021
1 map 1 2
2 mac 1 4
答案4
得分: 2
Another option is data.table
:
dcast(melt(setDT(df), id.vars = "PERIOD"), variable ~ PERIOD, value.var = "value")
variable 2020 2021
1: map 1 2
2: mac 1 4
英文:
Another option is data.table
:
dcast(melt(setDT(df), id.vars = "PERIOD"), variable ~ PERIOD, value.var = "value")
variable 2020 2021
1: map 1 2
2: mac 1 4
答案5
得分: 2
另一个选项是使用包janitor
library(janitor)
t(df) %>% row_to_name(1)
#> 2020 2021
#> map 1 2
#> mac 1 4
英文:
Another option is using package janitor
library(janitor)
t(df) %>% row_to_name(1)
#> 2020 2021
#> map 1 2
#> mac 1 4
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论