对不起基本问题,但我无法弄清楚如何更改字符串和数字。 我有一个数据框数据文件,列主题有28个不同的数字/主题(4,5,8,9,10,11,12等)。我需要将这些数字更改为字符串,例如' sbj04',' sbj05',' sbj08',' sbj09'' sbj10& #39;,' sbj11',' sbj12'等 我尝试了不同的东西,但他们没有工作。
datafile$subject = as.factor(datafile$subject) #it works
datafile$subject <- sub("^", "sbj", datafile$subject ) #it works, but all numbers become 'sbj4', 'sbj5', 'sbj8', 'sbj9', sbj10', etc.
以下代码无法返回我需要的内容
datafile[datafile$subject == "sbj4"] <- "sbj04"
datafile[datafile$subject == "sbj5"] <- "sbj05"
datafile[datafile$subject == "sbj8"] <- "sbj08"
datafile[datafile$subject == "sbj9"] <- "sbj09"
以下代码无法返回我需要的内容
datafile[datafile$subject == "sbj4",] <- datafile[datafile$subject == "sbj04",]
datafile[datafile$subject == "sbj5",] <- datafile[datafile$subject == "sbj05",]
datafile[datafile$subject == "sbj8",] <- datafile[datafile$subject == "sbj08",]
datafile[datafile$subject == "sbj9",] <- datafile[datafile$subject == "sbj09",]
以下代码无法返回我需要的内容
if (datafile$subject < 10) {
datafile$subject <- sub("^", "sbj0", datafile$subject )
} else{
datafile$subject <- sub("^", "sbj", datafile$subject )
}
答案 0 :(得分:0)
如果您实际拥有数值,一种简单的方法是使用sprintf
(在基数R中)。
示例:
> x <- 1:15
> sprintf("sbj%02.f", x)
[1] "sbj01" "sbj02" "sbj03" "sbj04" "sbj05" "sbj06" "sbj07" "sbj08" "sbj09"
[10] "sbj10" "sbj11" "sbj12" "sbj13" "sbj14" "sbj15"
因此,你应该尝试类似的东西:
datafile$subject <- sprintf("sbj%02.f", datafile$subject)