修改另一个字符列时,数字列将强制转换为字符列

时间:2017-11-10 16:44:41

标签: r coercion

我有一个包含两列的数据框,第一列包含数字,第二列包含数字。我的问题是:一旦我用另一个字符串替换第二列中的字符串,第一列就会从class数字强制转换为字符。这是一个例子:

df <- data.frame(num = c(1,2), char = c("a", "b"), stringsAsFactors = F)
class(df$num) # "numeric"
class(df$char) # "character"
df[df$char == "a", ] <- "c"
class(df$char) # "character" 
class(df$num) # "character" !!

这种行为的原因是什么以及如何阻止它?

2 个答案:

答案 0 :(得分:2)

我发现了我的错误:df[df$char == "a", ] <- "c"覆盖整行,这就是第一列被强制的原因。用“c”替换“a”的正确方法是:df$char[df$char == "a"] <- "c"

答案 1 :(得分:0)

更改后再看df:

$ { uuidgen -t && uuidgen -r && uuid -v1 && uuid -v4 ; } | xargs -L1 uuid -d

encode: STR:     5f441c74-c63a-11e7-8cb0-0242ac110002
        SIV:     126630312945231364299766443008257490946
decode: variant: DCE 1.1, ISO/IEC 11578:1996
        version: 1 (time and node based)
        content: time:  2017-11-10 17:12:46.679154.0 UTC
                 clock: 3248 (usually random)
                 node:  02:42:ac:11:00:02 (local unicast)
encode: STR:     d70f042a-c5ca-4726-b259-795e47fd1b95
        SIV:     285861988065069261246745478758429170581
decode: variant: DCE 1.1, ISO/IEC 11578:1996
        version: 4 (random data based)
        content: D7:0F:04:2A:C5:CA:07:26:32:59:79:5E:47:FD:1B:95
                 (no semantics: random data only)
encode: STR:     5f443b5a-c63a-11e7-8cd2-0242ac110002
        SIV:     126630939639996852130686378090112811010
decode: variant: DCE 1.1, ISO/IEC 11578:1996
        version: 1 (time and node based)
        content: time:  2017-11-10 17:12:46.679945.0 UTC
                 clock: 3282 (usually random)
                 node:  02:42:ac:11:00:02 (local unicast)
encode: STR:     09432e97-a1fc-4e05-9492-7c0c11ec0abc
        SIV:     12311880856012488273304867468361861820
decode: variant: DCE 1.1, ISO/IEC 11578:1996
        version: 4 (random data based)
        content: 09:43:2E:97:A1:FC:0E:05:14:92:7C:0C:11:EC:0A:BC
                 (no semantics: random data only)

所以当然$ num已成为角色。您的命令(由于其逗号语法)标识了要更改的整行。

不同的替换命令

> df
  num char
1   c    c
2   2    b
> 

做你所期待的。