[英]Changing a Column to an Observation in a Row in R
I am currently struggling to transition one of my columns in my data to a row as an observation.我目前正在努力将我的数据中的一列转换为一行作为观察。 Below is a representative example of what my data looks like:
以下是我的数据的代表性示例:
library(tidyverse)
test_df <- tibble(unit_name=rep("Chungcheongbuk-do"),unit_n=rep(2),
can=c("Cho Bong-am","Lee Seung-man","Lee Si-yeong","Shin Heung-woo"),
pev1=rep(510014),vot1=rep(457815),vv1=rep(445955),
ivv1=rep(11860),cv1=c(25875,386665,23006,10409),
abstention=rep(52199))
As seen above, the abstention
column exists at the end of my data frame, and I would like my data to look like the following:如上所示,
abstention
列存在于我的数据框的末尾,我希望我的数据如下所示:
library(tidyverse)
desired_df <- tibble(unit_name=rep("Chungcheongbuk-do"),unit_n=rep(2),
can=c("Cho Bong-am","Lee Seung-man","Lee Si-yeong","Shin Heung-woo","abstention"),
pev1=rep(510014),vot1=rep(457815),vv1=rep(445955),
ivv1=rep(11860),cv1=c(25875,386665,23006,10409,52199))
Here, abstentions are treated like a candidate, in the can
column .在这里,弃权被视为候选人,在
can
列中。 Thus, the rest of the data is maintained, and the abstention values are their own observation in the cv1
column.至此,数据的rest保持不变,弃权值是自己在
cv1
列中观察到的。
I have tried using pivot_wider
, but I am unsure how to use the arguments to get what I want.我曾尝试使用
pivot_wider
,但我不确定如何使用 arguments 来获得我想要的东西。 I have also considered t()
to transpose the column into a row, but also having a hard time slotting it back into my data.我还考虑过
t()
将列转换为一行,但也很难将其重新插入我的数据中。 Any help is appreciated!任何帮助表示赞赏! Thanks!
谢谢!
Here's a strategy what will work if you have multiple unit_names这是一个策略,如果您有多个 unit_names 将起作用
test_df %>%
group_split(unit_name) %>%
map( function(group_data) {
slice(group_data, 1) %>%
mutate(can="abstention", cv1=abstention) %>%
add_row(group_data, .) %>%
select(-abstention)
}) %>%
bind_rows()
Basically we split the data up by unit_name, then we grab the first row for each group and move the values around.基本上我们按 unit_name 拆分数据,然后我们抓取每个组的第一行并移动值。 Append that as a new row to each group, and then re-combine all the groups.
Append 即为每个组的新行,然后重新组合所有组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.