I am trying to copy data from one data frame to another data frame using strtrim
in a loop.
df <- data.frame(a = c("NEW0057-1", "NEW0058-2", "NEW0059-3", "NEW0060-4"))
trunc <- data.frame(matrix(nrow=nrow(df), ncol=1))
names(trunc) <- "b"
for (i in nrow(df)){
trunc[i,] <- strtrim(df[i,], 7)
}
head(trunc)
Above gives:
b
1 <NA>
2 <NA>
3 <NA>
4 NEW0060
However, I am looking for the following result:
b
1 NEW0057
2 NEW0058
3 NEW0059
4 NEW0060
The thread here says that preallocating data frame is not recommended. I think that's more for efficiency and should not cause the type of result I am getting above. In any case, I tried using a list as the post suggests and got a similar result:
df <- data.frame(a = c("NEW0057-1", "NEW0058-2", "NEW0059-3", "NEW0060-4"))
trunc <- list()
for (i in nrow(df)){
trunc[[i]] <- strtrim(df[i,], 7)
}
df = do.call("rbind", trunc)
I appreciate your time.
R version 3.0.3