dataframe - r apply function pads spaces to match character lengths -


i using apply generate strings data frame.

for example:

df2 <- data.frame(a=c(1:3), b=c(9:11)) apply(df2, 1, function(row) paste0("hello", row['a'])) apply(df2, 1, function(row) paste0("hello", row['b'])) 

works expect , generates

[1] "hello1" "hello2" "hello3" [1] "hello9" "hello10" "hello11" 

however, if have

df <- data.frame(a=c(1:3), b=c(9:11), c=c("1", "2", "3")) apply(df, 1, function(row) paste0("hello", row['a'])) apply(df, 1, function(row) paste0("hello", row['b'])) 

the output is

[1] "hello1" "hello2" "hello3" [1] "hello 9" "hello10" "hello11" 

can 1 please explain why padded space make strings same length in second case? can work around problem using gsub, have better understanding of why happens

this happening because apply transforms data.frame in matrix. see happens when coerce df matrix:

 as.matrix(df)        b    c   [1,] "1" " 9" "1" [2,] "2" "10" "2" [3,] "3" "11" "3" 

notice coerced character matrix , included space on " 9".


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -