Change one column's name in R - r

I need to change a specific column name in R. I used the following command but it did not change anything.
colnames(mydata[3])<-"newname"
"3" is the column number

colnames(mydata)[3] <- "newname". colnames is a vector itself, so just move your [3] outside it.

Related

Renaming Multiple Columns in R using Rename

I have already checked the forum for the solution but could not find the solution, hence, posting the problem here.
I am trying to change a name of a column using Rename, although the command is executed without any error but the names of the columns does not change.
I use this coderename(red,parts = category) Thanks
You need to pass a named vector as the second argument, and the names need to be quoted. Also, don't forget that you need to overwrite red with the result.
red <- reshape::rename(red, c(parts = "category"))
If you want to change multiple columns, add the items to the named vector you supply to the second argument.

How can i remove the first x number of characters of a column name from 200+ columns with each column being not the same number of characters

How can I remove a specific number of characters from a column name from 200+ column names for example: "Q1: GOING OUT?" and "Q5: STATE, PROVINCE, COUNTY, ETC" I just want to remove the "Q1: " and the "Q5: "I have looked around but haven't been able to find one where I don't have to manually rename them manually. Are there any functions or ways to use it through tidyverse? I have only been starting with R for 2 months.
I don't really have anything to show. I have considered using for loops and possibly using gsub or case_when, but don't really understand how to properly use them.
#probably not correctly written but tried to do it anyways
for ( x in x(0:length) and _:(length(CandyData)-1){
front -> substring(0:3)
back -> substring(4:length(CandyData))
print <- back
}
I don't really have any errors because I haven't been able to make it work properly.
Try this:
col_all<-c("Q1:GOING OUT?","Q2:STATE","Q100:PROVINCE","Q200:COUNTRY","Q299:ID") #This is an example.If you already have a dataframe ,you may get colnames by **col_all<-names(df)**
for(col in 1:length(col_all)) # Iterate over the col_all list
{
colname=col_all[col] # assign each column name to variable colname at each iteration
match=gregexpr(pattern =':',colname) # Find index of : for each colname(Since you want to delete characters before colon and keep the string succeeding :
index1=as.numeric(match[1]) # only first element is needed for index
if(index1>0)
{
col_all[col]=substr(colname,index1+1,nchar(colname))#Take substring after : for each column name and assign it to col_all list
}
}
names(df)<-col_all #assign list as column name of dataframe
The H 1 answer is still the best: sub() or gsub() functions will do the work. And do not fear the regex, it is a powerful tool in data management.
Here is the gsub version:
names(df) <- gsub("^.*:","",names(df))
It works this way: for each name, fetch characters until reaching ":" and then, remove all the fetched characters (including ":").
Remember to up vote H 1 soluce in the comments

read in csv file in R and make a list out of last column

Content of my.csv
project names,task names
Build Finances,Calculate Earnings
Build Roads,Calculate Equipment Costs
Buy Food, Calculate Grocery Costs
The code I'm using to read /tmp/my.csv into a variable/vector is:
taskNamesAndprojectNames <- read.csv("/tmp/my.csv", header=TRUE)
What I want to do is to grab the last column of my.csv file which has been put into the csvContent variable. And then make a list out of it.
So, something like this:
#!/usr/bin/Rscript
taskNamesAndprojectNames <- read.csv("/tmp/my.csv", header=TRUE)
#str(tasklists)
#tasklists
#tasklists[,ncol(tasklists)]
taskNames <- list(taskNamesAndprojectNames[,-1])
typeof(taskNames)
length(taskNames)
The problem with the above code is, when i run length on the taskNames variable/vector to confirm that it has the correct number of items or elements, I only get a response of 1. Which is not accurate.
[roywell#test01 data]$ ~/readincsv.r
[1] "list"
[1] 1
What am I doing wrong here? Can someone help me correct this code? What i want to do is grab the last column of an excel csv sheet, get the values in that last column and put them into a variable. Make a list out of it. Then iterate through the list to confirm that values/input provided by a user matches at least one of the elements in the list.
taskNames <- list(taskNamesAndprojectNames[,-1]) makes a list with one element that is a character vector of length 3.
It sounds like you are looking for a vector in this case:
taskNames <- taskNamesAndprojectNames[,-1]
typeof(taskNames)
[1] "character"
length(taskNames)
[1] 3

Two PASTE functions in a character vector

attach.files = c(paste("/users/joesmith/nosection_", currentDate,".csv",sep=""),
paste("/users/joesmith/withsection_", currentDate,".csv",sep=""))
Basically, if I did it like
c("nosection_051418.csv", "withsection_051418.csv")
And I did that manually it would work fine but since I'm automating this to run every day I can't do that.
I'm trying to attach files in an automated email but when I structure it like this, it doesn't work. How can I recreate this so that the character vector accepts it?
I thought your example implied the need for "parallel" inputs to the path stem, the first portion of the file name, and the date portions of those full paths. Consider this illustration of using a 2 item vector and a one item vector (produced by Sys.Date, replacing your "currentdate") to populate the %s positions in that sprintf string (suggested by #Gregor):
sprintf("/users/joesmith/%s_%s.csv", c("nosection", "withsection"), Sys.Date() )
[1] "/users/joesmith/nosection_2018-05-14.csv" "/users/joesmith/withsection_2018-05-14.csv"

R: Extract list element but without index number in output

This seems to be a beginner question but I couldn't find the answer anywhere. I know how to extract an element from a list using listname[[1]] but output will always include the index number like
[1] First element of the list
Same is true for using the name like listname$name or unlist(listname$name). All I want is
First element of the list
I could of course remove the index number using regex but I doubt that this is the way it should be :-)
The reason that the [1] appears is because all atomic types in R are vectors (of type character, numeric, etc), i.e. in your case a vector of length one.
If you want to see the output without the [1] the simples way is to cat the object:
> listname <- list("This is the first list element",
"This is the second list element")
> cat(listname[[1]], "\n")
This is the first list element
>

Resources