简体   繁体   中英

Numeric values in data frame

I have the following data frame which I use to call a function on all values from the column p.inits and plot them with the respective color from cols .

p.inits = c(0.5, 0.1, 0.9)
cols = c("red", "green", "blue")
data = data.frame(cbind(p.inits, cols))

foo = function (x) { print(1:x) }

for (i in 1:nrow(data)) {
  print(data$p.inits[i]
}

The function foo shows that something is not working the way I expected, since the output is:

[1] 1 2
[1] 1
[1] 1 2 3

also, p.inits evaluates to [1] 0.5 0.1 0.9 , whereas data$p.inits to this factor:

[1] 0.5 0.1 0.9
Levels: 0.1 0.5 0.9

My question is: what on God's green earth is happening? Why is the column p.inits not numeric? I just want to access the values 0.5, 0.1, 0.9 .

as.numeric(as.vector(data$p.inits)) does the trick, but this seems highly overcomplicated. Is this really the correct way?

Thank you.

Creating a data.frame is better done with data.frame call alone and not by converting to matrix with cbind and then converting to data.frame . The problem is how the matrix stores the elements as there is only a single class is normally allowed in matrix . Here, there is a character column and so we have all the elements converted to character . When we convert to data.frame , the default option stringsAsFactors = TRUE converts the character class to factor and that is the reason we have all factor class.

data <- data.frame(p.inits, cols)

should be the way

and if we don't need factor class then

data <- data.frame(p.inits, cols, stringsAsFactors= FALSE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM