Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

how to store the printed output from a function as a vector in R?

$
0
0

I have the following column from a dataframe

df <- data.frame(
 crime = as.character(c(115400, 171200, 91124, 263899, 67601, 51322)),
 stringsAsFactors=FALSE
)

I am using a function to extract the first two digits based on some condition as seen on the function below

for (i in df$crime){
  if (nchar(i)==6){
    print(substring(i,1,2))}
  else {print(substring(i,1,1))
  }
}

when I run this function I get the following output which is what I want

[1] "11"
[1] "17"
[1] "9"
[1] "26"
[1] "6"
[1] "5"

However, I want this to be saved as stand along vector. how do I do that?


Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>