Reputation: 9018
I want to create an empty data frame with one column holding character data and one column holding numeric data, and then populate that data frame.
dat<-as.data.frame(cbind(character(3),vector("numeric",3)))
dat
for (i in 1:3)
{
dat[i,1]<-as.character("f")
dat[i,2]<-i
}
dat
The results are below. As you can see I get all NA:
> dat
V1 V2
1 <NA> <NA>
2 <NA> <NA>
3 <NA> <NA>
Can you advise how to do it?
Upvotes: 5
Views: 43188
Reputation: 21047
What about creating a really empty data frame and adding the appropriate data?
dat <- as.data.frame(matrix(ncol=2, nrow=0))
for(i in 1:3) {
dat[i,1] = as.character('f')
dat[i,2] = i
}
dat
## V1 V2
##1 f 1
##2 f 2
##3 f 3
Upvotes: 2
Reputation: 2400
I think you want to use stingsAsFactors = F
dat<-as.data.frame(cbind(character(3),vector("numeric",3)), stringsAsFactors = F)
Upvotes: 0
Reputation: 193497
I don't know why you would want to do this, but here are some tips:
as.data.frame(cbind(...))
stringsAsFactors
Thus, you can try:
dat <- data.frame(character(3), numeric(3), stringsAsFactors = FALSE)
dat
# character.3. numeric.3.
# 1 0
# 2 0
# 3 0
for (i in 1:3)
{
dat[i,1]<-as.character("f")
dat[i,2]<-i
}
dat
# character.3. numeric.3.
# 1 f 1
# 2 f 2
# 3 f 3
Upvotes: 7