![](/img/trans.png)
[英]Naive Bayes prediction in R with reading characters as factors and without factors
[英]R - Convert a column of factors into binary characters without loss of information
我對R非常陌生,只是自學如何使用它。 我在Windows 7上使用R版本3.0.1(如果相關)。
我有麻煩轉換的數據factor
s轉換中的字符。 我的數據如下:
activity <- c("1","2","10","ZZ")
我想要的輸出是
activity <- c("01","02","10","ZZ")
其中,每個字符串(如果僅包含一個字符)都應以0
作為前綴(如上所示)。
我嘗試使用“ as.character”,但之前未添加零。 然后我找到了sprintf
並嘗試:
activity <- sprintf("%02d", (activity))
# [1] "01" "02" "03" "04"
這會在找到的任何單個數據前面添加零“ 0”,但麻煩的是它會修改數據的所有級別(如上所示)。
有人知道這里有什么問題嗎,我該如何解決? 謝謝。
您可以使用正則表達式,尤其是function sub
,用0
后跟該數字替換任何單個數字。 您應該這樣做來替換因子activity
的級別,以便相應地更改整個數據:
levels(activity) <- sub("^([0-9])$", "0\\1", levels(activity))
# [1] 01 02 10 ZZ
# Levels: 01 02 10 ZZ
編輯:如果您不僅要替換數字,還希望替換任何僅包含1個字符的字符串,則可以將[0-9]
替換為.
。 那是:
# suppose x is:
x <- c("1", "a", "Y", "!", "bb", "45")
x <- factor(x, levels=unique(x))
levels(x) <- sub("^(.)$", "0\\1", levels(x))
# [1] 01 0a 0Y 0! bb 45
# Levels: 01 0a 0Y 0! bb 45
閱讀?factor
,以了解將因子轉換回其值的正確方法。 正如您所看到的那樣,您需要謹慎對待因子,因為有時您會改變基礎索引而不是因子level
。
另外,您也不能“零填充”字符:
y <- factor(c('1', '2', '10', 'ZZ'))
x <- as.character(y)
sprintf('%02d', x)
Error in sprintf("%02d", x) :
invalid format '%02d'; use format %s for character objects
相反,您可以使用一個ifelse
:
ifelse(is.na(as.numeric(x)), x, sprintf('%02d', as.numeric(x)))
[1] "01" "02" "10" "ZZ"
但是正如Arun所示,正則表達式是解決問題的方法!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.