如何在 R 中将选定的行转换为单列

Ziz*_*zou 6 r dataframe dplyr data.table tidyr

我有一个需要转换的数据框。我需要根据列的值将唯一行更改为单列。

我的数据如下:

df1 <- data.frame(V1 = c("a", "a", "b", "b","b"), 
                  V2 = c("product1", "transport", "product1", "product2","transport"),
                  V3 = c("100", "10", "100", "100","10"))

> df1
  V1        V2  V3
1  a  product1 100
2  a transport  10
3  b  product1 100
4  b  product2 100
5  b transport  10
Run Code Online (Sandbox Code Playgroud)

我需要进行以下转换,并将 V3 的值除以 V1 中包含的产品数量。

> df2
  V1       V2 transport  V3
1  a product1        10 100
2  b product1         5 100
3  b product2         5 100
Run Code Online (Sandbox Code Playgroud)

akr*_*run 3

这是一种方法data.table- 转换为data.table( setDT),确保 'V3' 是numeric(用于除法 - 它是作为字符创建的),按 'V1' 分组,通过提取 'V3' 值来创建 '传输',其中 ' V2' 是“传输”并除以“V2”中非“传输”的元素数量,然后通过从“V2”中删除“传输”元素来对数据进行子集化

\n
library(data.table)\ndf1$V3 <- as.numeric(df1$V3)\nsetDT(df1)[, transport := V3[V2 == "transport"]/\n       sum(V2 != "transport"), by = V1]\ndf1[V2 != "transport"]\n       V1       V2    V3 transport\n   <char>   <char> <num>     <num>\n1:      a product1   100        10\n2:      b product1   100         5\n3:      b product2   100         5\n
Run Code Online (Sandbox Code Playgroud)\n
\n

或者另一种选择dplyr/tidyr

\n
library(dplyr)\nlibrary(tidyr)\ndf1 %>%\n   type.convert(as.is = TRUE) %>% \n   mutate(transport = case_when(V2 == 'transport' ~ V3)) %>% \n   group_by(V1) %>%\n   fill(transport, .direction = "downup") %>%\n   mutate(transport = transport/sum(V2 != "transport")) %>% \n   ungroup %>% \n   filter(V2 != "transport")\n# A tibble: 3 \xc3\x97 4\n  V1    V2          V3 transport\n  <chr> <chr>    <int>     <dbl>\n1 a     product1   100        10\n2 b     product1   100         5\n3 b     product2   100         5\n
Run Code Online (Sandbox Code Playgroud)\n