假設我有以下 df:
teamid scores
1 10
2 11
其中第一個數字(即1 0 )是第一個分數,第二個數字(即 1 0)是第二個分數。我如何將 df 中的分數相加?
結果 df:
teamid Combinedscore
1 1
2 2
uj5u.com熱心網友回復:
這是一個tidyr和dplyr解決方案:
library(tidyr)
library(dplyr)
df %>%
extract(scores,
into = c("1","2"),
regex = "(.)(.)",
convert = TRUE) %>%
mutate(combinedScore = rowSums(across(c("1","2")))) %>%
select(-c(2,3))
teamid combinedScore
1 1 1
2 2 2
資料:
df <- data.frame(
teamid = c(1:2),
scores = c(10, 11)
)
uj5u.com熱心網友回復:
我們可以使用read.fwffrombase R將分數列拆分為多列,并獲取rowSums每個數字的 'Combinedscore'
df$Combinedscore <- rowSums(read.fwf(textConnection(as.character(df$scores)),
widths = rep(1, max(nchar(df$scores)))), na.rm = TRUE)
-輸出
> df
teamid scores Combinedscore
1 1 10 1
2 2 11 2
資料
df <- structure(list(teamid = 1:2, scores = 10:11),
class = "data.frame", row.names = c(NA,
-2L))
uj5u.com熱心網友回復:
這是一個使用with的基本 Rstrsplitsapply
df$Combinedscore <-
colSums( sapply( strsplit( as.character(df$scores),"" ), as.numeric ) )
teamid scores Combinedscore
1 1 10 1
2 2 11 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/369043.html
