Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change the value of the last element to the same as 1st element?

Problem: Write a code that changes the value of the 4th element of vector y to 6, then changes the value of last element to the same as 1st element and finally calculates the sum of all the elements.

Attempted solution:

y[4]<-6
y["last"]<- 1
sum(y)

Can’t figure out what’s wrong with this… help is much appreciated!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your attempted solution is almost correct. The only problem is that the y["last"] line will not work because there is no element in the vector named last. You can fix this by using the length() function to get the length of the vector, and then using that value to index into the vector. For example:

y[length(y)] <- 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading