Update data frame via function doesn't work

Viewed 44450

I ran into a little problem using R…

In the following data frame

test <- data.frame(v1=c(rep(1,3),rep(2,3)),v2=0) 

I want to change values for v2 in the rows where v1 is 1.

test[test$v1==1,"v2"] <- 10

works just fine.

test
  v1 v2
1  1 10
2  1 10
3  1 10
4  2  0
5  2  0
6  2  0

However, I need to do that in a function.

test <- data.frame(v1=c(rep(1,3),rep(2,3)),v2=0)

test.fun <- function (x) {
    test[test$v1==x,"v2"] <- 10
    print(test)
}

Calling the function seems to work.

test.fun(1)
  v1 v2
1  1 10
2  1 10
3  1 10
4  2  0
5  2  0
6  2  0

However, when I now look at test:

test
  v1 v2
1  1  0
2  1  0
3  1  0
4  2  0
5  2  0
6  2  0

it didn’t work. Is there a command that tells R to really update the data frame in the function? Thanks a lot for any help!

6 Answers

* I have created a function called read__csv I want to access that same data to other r function*

read__csv <- function(files_csv) {
  print(files_csv)
  # set R workign directory as current R file path
  setwd(system("pwd", intern = T) )
  print( getwd() )
  data<-read.csv(files_csv,header = TRUE,na.strings=0)
  print(data)
  assign("data", data, envir = .GlobalEnv)
 #create data varible to r global envrioment 
}

#R Funtion calling
read__csv("csv.csv")

print(data)
Related