Sometimes you may want to export your data from R (.Rdata) to another format, such as a TXT file (a tab-delimited text file) or a CSV file (a comma-separated values file). In addition, the most widely used statistical packages are SAS, Stata, and SPSS, so here we will also show how you can export data to those formats.
In the code below, dt is the name of the dataset in R, and mydata is the name of the exported file.
(1) Exporting data to TXT (tab-delimited text file):
write.table(dt, "mydata.txt", sep="\t")
(2) Exporting data to CSV:
write.table(dt, file="mydata.csv",sep=",",row.names=F)
(3) Exporting data to SPSS. Here it is necessary to load the foreign package first:
require(foreign) write.foreign(dt, "mydata.txt", "mydata.sps", package="SPSS")
(4) Exporting data to Stata:
require(foreign) write.dta(dt, "mydata.dta")
(5) Exporting data to SAS:
library(foreign) write.foreign(dt, "mydata.txt", "mydata.sas", package="SAS")
We hope you find this short post useful.
I have a dataframe (1349 obs. of 14 var.) with the categorical variables “Agree”, “Disagree” and “Not sure”.
How can I replace Agree with 0, Disagree with 1 and not sure with 0.5 in the whole dataframe?
When I try, it either just gives me the levels or it deletes everything except the three values 0,1 and 0.5.
I know this is basic but I just can’t figure it out myself….
test this:
data$variable2 = with(data, ifelse(variable==”Agree”, 0, ifelse(variable==”Disagree”, 1, 0.5)))
How to merge two columns together to create a new column. e.g.
D1 I H D2
1 64 57 8
2 71 59 10
3 53 49 6
4 67 62 11
5 55 51 8
6 58 50 7
We want merge D1 and D2 together to create a new variable “D” which is 3-digit, thus, for any D2 we want it becomes 2-digit number by adding “0” in front of any 1-digit D2 number, so it becomes:
D1 I H D2 D
1 64 57 8 108
2 71 59 10 210
3 53 49 6 306
4 67 62 11 411
5 55 51 8 508
6 58 50 7 607
How to do it in R?
all = merge(dataset1, dataset2, by=”D1″)
I want to merge two columns, not two datasets.
I tried this:
1) # Create D2new to add 0 in front of D2, if needed
D2new<-sprintf("%02.0f", W2.data$D2)
2) # Combine D1 and D2new to create D
W3.data$D <- paste(W2.data$D1,W2.data$D2new)
Sounds OK, but there is a space between D1 and D2new in the new variable D. Now it looks like:
D1 I H D2 D
1 64 57 8 1 08
2 71 59 10 2 10
3 53 49 6 3 06
4 67 62 11 4 11
5 55 51 8 5 08
6 58 50 7 6 07
How to remove the space in D?
use paste(x,y,sep=””) within the paste command
I have tried the function above to rename variable but the variable has just disappeared…What the hell have I done wrong?
did you loaded the dataset?
use names(dataset_name) to get all vatiables in your dataset. new_variable <- old_variable
Thanks for the reply. Yes, I did. Other functions that should work didn’t. The only function that worked fine to rename was :
names(dataset_name)[names(dataset_name)==”old”] <- "new"
how to add (age,gender) in bipartite graph of person-hobbies using R???