gpt4 book ai didi

r - 如何更改 R data.frame 中的行名称?

转载 作者:行者123 更新时间:2023-12-04 09:28:40 26 4
gpt4 key购买 nike

我想将 DF 中的 station 重命名为 DA056HappyAB786Sad .

library(tidyverse)

DF1 <- data.frame(Station = rep("DA056",3), Level = 100:102)
DF2 <- data.frame(Station = rep("AB786",3), Level = 201:203)
DF <- bind_rows(DF1,DF2)

最佳答案

我们可以使用 factorlabels指定为相应的 levels

library(dplyr)
DF <- DF %>%
mutate(Station = factor(Station, levels = c("DA056", "AB786"),
labels = c("Happy", "Sad")))

DF$Station
#[1] Happy Happy Happy Sad Sad Sad
#Levels: Happy Sad

或与 recode
DF %>%
mutate(Station = recode(Station, DA056 = 'Happy', AB786 = 'Sad'))
# Station Level
#1 Happy 100
#2 Happy 101
#3 Happy 102
#4 Sad 201
#5 Sad 202
#6 Sad 203

如果要更改的值很多,更好的选择是在创建 key/val 数据集后加入
keyval <- data.frame(Station = c("DA056", "AB786"),
val = c("Happy", "Sad"), stringsAsFactors = FALSE)
DF %>%
left_join(keyval) %>%
mutate(Station = coalesce(val, Station))

或与 base R
DF$Station <- with(df,  factor(Station, levels = c("DA056", "AB786"), 
labels = c("Happy", "Sad")))

关于r - 如何更改 R data.frame 中的行名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62923844/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com