I'm experimenting with R and I try to interchangeably simulate and write data to a file. I tried out many variants for example:
connection<-file("file.txt", open="w")
for (i in 1:2){
X<-runif(3,0,1)
writeLines(as.character(X), con=connection, sep="\n")
}
close(connection)
But what I get is
0.442033957922831
0.0713443560525775
0.950616024667397
0.0807233764789999
0.186026858631521
0.658676357707009
instead of something like
0.442033957922831 0.0713443560525775 0.950616024667397
0.0807233764789999 0.186026858631521 0.658676357707009
Could you explain me what I'm doing wrong?
We can paste the elements in 'X' to a single string and then use sep='\n', otherwise after each element, it is jumping to nextline
connection<-file("file.txt", open="w")
for (i in 1:2){
X<-runif(3,0,1)
writeLines(paste(X, collapse=" "), con=connection, sep="\n")
}
close(connection)
-output
Instead of writing line by line in a for loop we can create the string once and write it in the text file in one-go.
We can use replicate to repeat the runif code n times, paste the numbers row-wise, and paste them again collapsing with a new line character.
temp <- paste0(apply(t(replicate(2, runif(3,0,1))), 1, paste, collapse = ' '),
collapse = '\n')
connection <- file("file.txt")
writeLines(temp, connection)
close(connection)
where temp gives us a string of length one which looks like this :
temp
#[1] "0.406911700032651 0.416268902365118 0.698520892066881\n0.96398281189613 0.834513065638021 0.655840792460367"
which looks in text file as :
cat(temp)
#0.406911700032651 0.416268902365118 0.698520892066881
#0.96398281189613 0.834513065638021 0.655840792460367
Related
I have code in RStudio which imports a csv based on criteria by using paste function.
Name <- "Sam"
Location <- "Barnsley"
Code <- "A"
Test2 <- read_csv(paste("C:/Users/....,Opposition , " (",Code,")/Vs ",Location, " (",Code,") Export for ",Name,".csv",sep = ""),skip = 8)
I usually follow this import code by a few lines of code for calculations. For arguments sake: Run Code Series
I would like to recreate this code in order to create a list of names, and have the code run through each 1 by 1 followed by running the code.
Desired:
Name <- c("Sam","David","Paul","John")
Then be able to run the import code and have it Run Code Series after each import before importing the next name.
I believe from your question that you want to end with a separate dataframe for each name. If so, you could do it like this:
Names <- c("Sam","David","Paul","John")
Location <- "Barnsley"
Code <- "A"
for(i in Names){
Test2 <- read_csv(paste("C:/Users/....,Opposition" , " (", Code,")/Vs ", Location, " (",Code,") Export for ", i, ".csv", sep = ""), skip = 8)
Run Code Series
assign(paste("df_for_", i, sep = ""), Test2)
}
This will go through your list of names and within the loop, open the file as Test2. You perform your calculations on Test2, and then assign it to a dataframe for the particular name in the list using paste. Also your quotes in your read_csv line do not match up, so that will need to be corrected.
I'm very new to R so may still be thinking in spreadsheets. I'd like to loop a list of names from a vector (list) through a function (effect) and append text to the front and end of the name a bit of text ("data$" and ".time0" or ".time1") so it references a specific vector of a dataframe I already have loaded (i.e., data$variable.time0 and data$variable.time1).
Paste just gives me a character named "data$variable.time0" or "data$variable.time1", rather than referencing the vector of the dataframe I want it to. Can I convert this to a reference somehow?
for (i in list){
function(i)
}
effect <- function(i){
time0 <- paste("data$",i,".time0", sep = ""))
time1 <- paste("data$",i,".time1", sep = ""))
#code continues but not relevant here
}
You can use eval(parse(text = "...")) to evaluate characters.
Try
time0 <- eval(parse(text = paste("data$",i,".time0", sep = ""))))
within your loop.
I would like to use readLines function to read the text file line by line
69C_t.txt
Also, I would like to write a simple for loop with condition to extract the identical lines in two files.
69C_t <- "69C_t.txt"
conn <- file(69C_t,open="r")
t <-readLines(conn)
69C_b <- "69C_b.txt"
conn <- file(69C_b,open="r")
b <-readLines(conn)
for (i in 1:length(t)){
for (j in 1:length(b)){
if (i==j)
write(t[i], file = "overlap.txt")
}
}
close(tumor)
However, it seems only print out the first line.
Can someone please have a check ?
A faster approach would be, instead of the loop
writeLines(t[t %in% b],"overlap.txt")
How about adding append in the write function:
write(t[i], file = "overlap.txt", append = TRUE)
I want to read a xlsx file and I want to convert the data in the file into a long text string. I want to format this string in an intelligent manner, such as each row is contained in parentheses “()”, and keep the data in a comma separated value string. So for example if this was the xlsx file looked like this..
one,two,three
x,x,x
y,y,y
z,z,z
after formatting the string would look like
header(one,two,three)row(x,x,x)row(y,y,y)row(z,z,z)
How would you accomplish this task with R?
my first instinct was something like this… but I can’t figure it out..
library(xlsx)
sheet1 <- read.xlsx("run_info.xlsx",1)
paste("(",sheet1[1,],")")
This works for me:
DF <- read.xlsx("run_info.xlsx",1)
paste0("header(", paste(names(DF), collapse = ","), ")",
paste(paste0("row(", apply(DF, 1, paste, collapse = ","), ")"),
collapse = ""))
# [1] "header(one,two,three)row(x,x,x)row(y,y,y)row(z,z,z)"
I want to replace only ONE line of my text connection in R, but I find that if the replace string is longer it anyway goes into the next line... how can I prevent this?
An example:
Let's say I make a 2-row text file, and open it for reading + writing:
write(rbind("This is the first line</a>", "This is the second line"),"test.txt")
fileName <- "test.txt"
FileToChange <- file(fileName, "r+b")
# readLines(FileToChange,1)
if you uncomment that last one, you can see that it is in fact 2 lines)
OK, now I read in line 1, and replace it w/ the longer string:
FileToChange.line <- readLines(FileToChange,1)
FileToChange.line
newStuff <-"EVIL NEW TEXT"
replacedText <- gsub("</a", paste(" ", newStuff," </a",sep=""), FileToChange.line)
replacedText
And here I try to replace JUST the first line:
writeLines(replacedText, FileToChange, sep="\n")
close(FileToChange)
This will give:
This is the first line EVIL NEW TEXT
cond line
See how the second line is 'eaten up'? This is because it's simply replacing characters... but it I'm not using writeChar(), I'm using 'writeLines(). I also tried to usewrite()` to no avail.
What gives?
Thanks for looking!
Found it. The solution was to use an intermediary. Then the steps are:
Read entire file and assign to an array
Replace first entry of that array
Assign corrected array back to the file.
Winning code follows:
write(rbind("This is the first line</a>", "This is the second line"),"test.txt")
fileName <- "test.txt"
FileToChange <- file(fileName, "r+b")
a <- readLines(FileToChange)
FileToChange.line <- a[1]
newStuff <-"EVIL NEW TEXT"
a[1] <- gsub("</a", paste(" ", newStuff," </a",sep=""), a[1])
write(a,fileName)
close(FileToChange)