【问题标题】:Replace all string values to '1' [duplicate]将所有字符串值替换为“1”[重复]
【发布时间】:2017-01-25 10:10:00
【问题描述】:

我在 R 中有一个数据框,其中所有单元格都包含“0”或一个单词(4-6 个字母的短字符串)。我想将所有这些字符串值替换为“1”。我看到很多选项替换特定的单词或字符,但由于我有很多不同的单词,我只想说'将所有字符串值替换为数字'1')。

非常感谢您的帮助!

【问题讨论】:

标签: r string replace numeric


【解决方案1】:
x <- c("0","a","short","sentence")

as.numeric(x != "0")
[1] 0 1 1 1

要使用 data.frame,您必须使用 lapply 遍历列并转换回来:

y <- data.frame(x,x,x)
data.frame(lapply(y, function(x) as.numeric(x!="0")))
  x x.1 x.2
1 0   0   0
2 1   1   1
3 1   1   1
4 1   1   1

【讨论】:

  • 更好(imo):as.numeric(x != "0")
  • 您还需要在 data.frame @James 中加入一个示例
【解决方案2】:

我们可以使用

 replace(x, x!="0", 1)

或者只是

as.integer(x!= "0")

如果我们有一个 data.frame

df1[] <- lapply(df1, function(x) as.integer(x!="0"))

【讨论】:

    【解决方案3】:

    假设 df 是您的数据。假设你的字符串都是character 变量

    df = data.frame(a = c("joel", "0", "wilso"), b = c(1:3))
    df$a <- as.character(df$a)
    df[df != '0']='1'
    df
    #  a b
    #1 1 1
    #2 0 1
    #3 1 1
    

    df = data.frame(a = c("j", "0", "w"), b = c(1:3), 
                    c = 4:6, d = c("eng", "0", "aus"))
    
    data.frame(lapply(df, function(x) { 
                             if(is.factor(x)) {
                               x <- as.character(x)
                             }
                             x[x!="0"]="1"
                             x}))
    #  a b c d
    #1 1 1 1 1
    #2 0 1 1 0
    #3 1 1 1 1
    

    【讨论】:

      猜你喜欢
      • 2019-01-11
      • 1970-01-01
      • 2020-09-11
      • 2015-02-28
      • 2020-05-09
      • 2018-10-25
      • 2017-05-01
      • 2021-05-13
      • 1970-01-01
      相关资源
      最近更新 更多