[英]Create a new column by aggregating multiple columns in R
背景
我有一個數據集 df,我想在其中聚合多個列並創建一個新列。 我需要將 Type、Span 和 Population 列相乘並創建一個新的 Output 列
ID Status Type Span State Population
A Yes 2 70% Ga 10000
所需 output
ID Status Type Span State Population Output
A Yes 2 70% Ga 10000 14000
輸入
structure(list(ID = structure(1L, .Label = "A ", class = "factor"),
Status = structure(1L, .Label = "Yes", class = "factor"),
Type = 2L, Span = structure(1L, .Label = "70%", class = "factor"),
State = structure(1L, .Label = "Ga", class = "factor"), Population = 10000L), class = "data.frame",
row.names = c(NA,
-1L))
這是我嘗試過的
df %>%
mutate(Output = Type * Span * Population)
在這里,我們正在根據來自不同列的輸入創建一個新列。 我們可以使用mutate
來獲得Population
的Span
百分比並乘以“類型”。 請注意,'Span' 不是數字,因為它有%
,所以我們用parse_number
除以 100 提取數字部分,然后乘以 Population 和 'Type'
library(dplyr)
df %>%
mutate(Output = Type * Population * readr::parse_number(as.character(Span))/100)
# ID Status Type Span State Population Output
#1 A Yes 2 70% Ga 10000 14000
如果“類型”、“人口”列不是數字,最好使用as.numeric(as.character(df$Type))
和“人口”(假設它們是factor
類)轉換為numeric
。 另一個選項是type.convert(df, as.is = TRUE)
然后處理修改后的 class 數據集
我們可以使用sub
刪除'%'
符號,轉換為數字並乘以值。
這可以在基礎 R 中完成,如下所示:
df$output <- with(df, Type * as.numeric(sub('%', '', Span)) * Population/100)
df
# ID Status Type Span State Population output
#1 A Yes 2 70% Ga 10000 14000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.