Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 根据条件更改字符串_R_String - Fatal编程技术网

R 根据条件更改字符串

R 根据条件更改字符串,r,string,R,String,我有一个像下面这样的数据帧 我想在year变量中字符串的开头添加一个字符,它将基于第一个字符进行变量化 year <- c("991", "990", "985", "975", "001", "003") name <- c("John", "Anna", "Amy", "Sarah", "Bob", "John") test <- data.frame(year, name) 有了这个,我得到了第一行的第一个字符,但我不知道如何将其放入循环中,然后在其中添加一个条件 这

我有一个像下面这样的数据帧

我想在year变量中字符串的开头添加一个字符,它将基于第一个字符进行变量化

year <- c("991", "990", "985", "975", "001", "003")
name <- c("John", "Anna", "Amy", "Sarah", "Bob", "John")

test <- data.frame(year, name)

有了这个,我得到了第一行的第一个字符,但我不知道如何将其放入循环中,然后在其中添加一个条件

这里有一个嵌套的
ifelse
语句

ifelse(substring(test$year, 1, 1) == 9, paste0(1, test$year), 
       ifelse(substring(test$year, 1, 1) == 0, paste0(2, test$year), paste0(7, test$year)))
#[1] "1991" "1990" "1985" "1975" "2001" "2003"

这是一个嵌套的
ifelse
语句

ifelse(substring(test$year, 1, 1) == 9, paste0(1, test$year), 
       ifelse(substring(test$year, 1, 1) == 0, paste0(2, test$year), paste0(7, test$year)))
#[1] "1991" "1990" "1985" "1975" "2001" "2003"
library(data.table)
library(stringr)
setDT(test)

test[str_detect(year, "^0"), new := paste0("2", year)]
test[str_detect(year, "^9"), new := paste0("1", year)]