views:

86

answers:

1

In R, how can I overwrite the first values of a long vector with values obtained from a file, where the file contains possibly fewer values?

Example:

# fill with n=100 values
vec1 <- runif(100)

# read m values, where m <= n
vec2 <- scan("myfile", sep="\n")

# now want to set the first m values of vec1 
# to the values in vec2

I could walk through vec2 and copy the values into vec1, but I think there should be a more efficient way?

+6  A: 
R> set.seed(1)
R> vec1 <- runif(100)
R> vec2 <- 1:20

R> vec1[1:length(vec2)] <- vec2
R> vec1
  [1]  1.00000  2.00000  3.00000  4.00000  5.00000  6.00000  7.00000  8.00000
  [9]  9.00000 10.00000 11.00000 12.00000 13.00000 14.00000 15.00000 16.00000
 [17] 17.00000 18.00000 19.00000 20.00000  0.93471  0.21214  0.65167  0.12556
 [25]  0.26722  0.38611  0.01339  0.38239  0.86969  0.34035  0.48208  0.59957
 [33]  0.49354  0.18622  0.82737  0.66847  0.79424  0.10794  0.72371  0.41127
 [41]  0.82095  0.64706  0.78293  0.55304  0.52972  0.78936  0.02333  0.47723
 [49]  0.73231  0.69273  0.47762  0.86121  0.43810  0.24480  0.07068  0.09947
 [57]  0.31627  0.51863  0.66201  0.40683  0.91288  0.29360  0.45907  0.33239
 [65]  0.65087  0.25802  0.47855  0.76631  0.08425  0.87532  0.33907  0.83944
 [73]  0.34668  0.33377  0.47635  0.89220  0.86434  0.38999  0.77732  0.96062
 [81]  0.43466  0.71251  0.39999  0.32535  0.75709  0.20269  0.71112  0.12169
 [89]  0.24549  0.14330  0.23963  0.05893  0.64229  0.87627  0.77891  0.79731
 [97]  0.45527  0.41008  0.81087  0.60493
rcs