我有一個這樣的資料集
我想在不同的行上分開“錢”、“收入”和“貸款”。我的意思是,我想得到這個:
我的第一個想法是:復制該行,然后洗掉額外的值以獲得期望的結果。我懂了 :
但我堅持要洗掉紅色的值。我們怎樣才能做到這一點?
這是我的代碼:
mydata = data.frame(
name = "Vince",
date = "16/05/1977",
money = 20,
city = "NY",
income = 100,
country = "USA",
car = "Porsche",
loan = 250
)
duplicated_data = do.call("rbind", replicate(3, mydata, simplify = FALSE))
一些幫助將不勝感激
uj5u.com熱心網友回復:
在基數 R 中,轉換為矩陣,然后用 NA 替換非對角線值
cols = c("money", "income", "loan")
mat <- as.matrix(duplicated_data[cols])
duplicated_data[cols] <- ifelse(row(mat) == col(mat), mat, NA) #Replace with NA
或者如果您可以使用 0 而不是 NA,那可能會更簡單:
duplicated_data[cols] <- diag(diag(mat)) #Replace with 0
輸出
name date money city income country car loan
1 Vince 16/05/1977 20 NY NA USA Porsche NA
2 Vince 16/05/1977 NA NY 100 USA Porsche NA
3 Vince 16/05/1977 NA NY NA USA Porsche 250
uj5u.com熱心網友回復:
library(tidyverse)
pivot_longer(mydata,
cols = c(money, income, loan),
names_to = "stat") |>
mutate(money = ifelse(stat == "money", value, NA),
income = ifelse(stat == "income", value, NA),
loan = ifelse(stat == "loan", value, NA)) |>
select(-stat,-value)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/505744.html
上一篇:根據條件將資料幀轉換為多個資料幀