我目前正在用 R 編碼并將兩個資料幀合并在一起,這樣我就可以將所有資訊包含在一起,但我不希望將一列“成本”重復多次(這是由于最后 3 列的唯一值) . 我希望它只在第一列中包含成本 100,然后對于列“狀態”、“市場”、“日期”和“成本”與上面相同的每個其他實體。我附上了資料框的樣子以及我希望將其更改為的內容。謝謝!
目前的樣子

它應該是什么樣子

uj5u.com熱心網友回復:
請使用本例中的索引:
name_of_your_dataset[nrow_init:nrow_fin, ncol] <- NA
在您的情況下,假設您的資料集名稱為“資料”
data[2:4,4]<- NA
只需留下積極的反饋,如果我有用,請投票給這個答案。
uj5u.com熱心網友回復:
這是一個使用重復資料框(df)的解決方案
State Market Date Cost Word format Type
1 AZ Phoenix 10-20-2020 100 HELLO AM Sports related
2 AZ Phoenix 10-21-2020 NA GOODBYE PM Non Sports related
3 AZ Phoenix 10-22-2020 NA YES FM Country
4 AZ Phoenix 10-23-2020 NA NONE CM Rock
將重復項設定為 NA
df$Cost[duplicated(df$Cost)] <- NA
輸出:
State Market Date Cost Word format Type
1 AZ Phoenix 10-20-2020 100 HELLO AM Sports related
2 AZ Phoenix 10-21-2020 NA GOODBYE PM Non Sports related
3 AZ Phoenix 10-22-2020 NA YES FM Country
4 AZ Phoenix 10-23-2020 NA NONE CM Rock
uj5u.com熱心網友回復:
該列Date是不同的,所以我認為您想要Cost為每個值State和Market組合替換重復。
library(dplyr)
df <- df %>%
group_by(State, Market) %>%
mutate(Cost = replace(Cost, duplicated(Cost), NA)) %>%
ungroup
df
# State Market Date Cost Word format Type
# <chr> <chr> <chr> <dbl> <chr> <chr> <chr>
#1 AZ Phoenix 10-20-2020 100 HELLO AM Sports related
#2 AZ Phoenix 10-21-2020 NA GOODBYE PM Non Sports related
#3 AZ Phoenix 10-22-2020 NA YES FM Country
#4 AZ Phoenix 10-23-2020 NA NONE CM Rock
資料
如果您以可重現的格式提供資料,則更容易獲得幫助
df <- structure(list(State = c("AZ", "AZ", "AZ", "AZ"), Market = c("Phoenix",
"Phoenix", "Phoenix", "Phoenix"), Date = c("10-20-2020", "10-21-2020",
"10-22-2020", "10-23-2020"), Cost = c(100, 100, 100, 100), Word = c("HELLO",
"GOODBYE", "YES", "NONE"), format = c("AM", "PM", "FM", "CM"),
Type = c("Sports related", "Non Sports related", "Country",
"Rock")), row.names = c(NA, -4L), class = "data.frame")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/318518.html
