0

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

Community
  • 1
  • 1
sedeh
  • 7,083
  • 6
  • 48
  • 65
  • 2
    I don't understand why you are using a loop at all here. `strtrim(df$a,7)` should trim all the values at once. If you want to create a new data.frame from that, use `trunc <- data.frame(b=strtrim(df$a,7))` – MrFlick Jul 05 '14 at 05:04
  • 2
    Try `for (i in 1:nrow(df))`. You are missing the `1:` part. That said, @MrFlick is right. – Jota Jul 05 '14 at 05:05
  • You both are very correct! I missed it. Thanks for the pointer. – sedeh Jul 05 '14 at 05:26

1 Answers1

0

As mentioned in the comments, there's no need for a loop here.

Also, this seems like a good case where within can be used

> ( trunc <- within(df, { b <- strtrim(a, 7); rm(a) }) )
#         b
# 1 NEW0057
# 2 NEW0058
# 3 NEW0059
# 4 NEW0060
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245